Много доработок
This commit is contained in:
parent
ea2b4a795f
commit
36c2c3085e
22
README.md
22
README.md
|
@ -18,3 +18,25 @@
|
|||
|
||||
Когда все откопируется, выполняем команду:
|
||||
`python3 ~/installSoft/install.py`
|
||||
|
||||
Заметки:
|
||||
Устанавливаем Python 3.7
|
||||
|
||||
В питон устанавливаем venv:
|
||||
`sudo apt-get install python3.7-venv`
|
||||
|
||||
После установки venv находясь в нужной папке с проектом мы восстанавливаем из фриза виртуальное окружение:
|
||||
`pip3 install -r requirements.txt`
|
||||
|
||||
а чтоб это было на месте нужно перед этим
|
||||
1. создать виртуальное окружение
|
||||
`python3.7 -m venv install-soft-on-Astra-linux`
|
||||
2. активировать его в исполняемой среде
|
||||
`source install-soft-on-Astra-linux/bin/activate`
|
||||
3. установить в него нужное количество пакетов
|
||||
просмотреть список пакетов можно командой: `pip3 list`
|
||||
установить пакеты:
|
||||
ldap3 командой `python3.7 -m pip install ldap3`
|
||||
#ldap (python-ldap) командой `python3.7 -m pip install python-ldap`
|
||||
4. Заморозить установленные пакеты:
|
||||
`python3 -m pip freeze > requirements.txt`
|
|
@ -0,0 +1,76 @@
|
|||
# This file must be used with "source bin/activate" *from bash*
|
||||
# you cannot run it directly
|
||||
|
||||
deactivate () {
|
||||
# reset old environment variables
|
||||
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
|
||||
PATH="${_OLD_VIRTUAL_PATH:-}"
|
||||
export PATH
|
||||
unset _OLD_VIRTUAL_PATH
|
||||
fi
|
||||
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
|
||||
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
|
||||
export PYTHONHOME
|
||||
unset _OLD_VIRTUAL_PYTHONHOME
|
||||
fi
|
||||
|
||||
# This should detect bash and zsh, which have a hash command that must
|
||||
# be called to get it to forget past commands. Without forgetting
|
||||
# past commands the $PATH changes we made may not be respected
|
||||
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
|
||||
hash -r
|
||||
fi
|
||||
|
||||
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
|
||||
PS1="${_OLD_VIRTUAL_PS1:-}"
|
||||
export PS1
|
||||
unset _OLD_VIRTUAL_PS1
|
||||
fi
|
||||
|
||||
unset VIRTUAL_ENV
|
||||
if [ ! "$1" = "nondestructive" ] ; then
|
||||
# Self destruct!
|
||||
unset -f deactivate
|
||||
fi
|
||||
}
|
||||
|
||||
# unset irrelevant variables
|
||||
deactivate nondestructive
|
||||
|
||||
VIRTUAL_ENV="/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux"
|
||||
export VIRTUAL_ENV
|
||||
|
||||
_OLD_VIRTUAL_PATH="$PATH"
|
||||
PATH="$VIRTUAL_ENV/bin:$PATH"
|
||||
export PATH
|
||||
|
||||
# unset PYTHONHOME if set
|
||||
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
|
||||
# could use `if (set -u; : $PYTHONHOME) ;` in bash
|
||||
if [ -n "${PYTHONHOME:-}" ] ; then
|
||||
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
|
||||
unset PYTHONHOME
|
||||
fi
|
||||
|
||||
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
|
||||
_OLD_VIRTUAL_PS1="${PS1:-}"
|
||||
if [ "x(install-soft-on-Astra-linux) " != x ] ; then
|
||||
PS1="(install-soft-on-Astra-linux) ${PS1:-}"
|
||||
else
|
||||
if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
|
||||
# special case for Aspen magic directories
|
||||
# see http://www.zetadev.com/software/aspen/
|
||||
PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
|
||||
else
|
||||
PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
|
||||
fi
|
||||
fi
|
||||
export PS1
|
||||
fi
|
||||
|
||||
# This should detect bash and zsh, which have a hash command that must
|
||||
# be called to get it to forget past commands. Without forgetting
|
||||
# past commands the $PATH changes we made may not be respected
|
||||
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
|
||||
hash -r
|
||||
fi
|
|
@ -0,0 +1,37 @@
|
|||
# This file must be used with "source bin/activate.csh" *from csh*.
|
||||
# You cannot run it directly.
|
||||
# Created by Davide Di Blasi <davidedb@gmail.com>.
|
||||
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
|
||||
|
||||
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
|
||||
|
||||
# Unset irrelevant variables.
|
||||
deactivate nondestructive
|
||||
|
||||
setenv VIRTUAL_ENV "/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux"
|
||||
|
||||
set _OLD_VIRTUAL_PATH="$PATH"
|
||||
setenv PATH "$VIRTUAL_ENV/bin:$PATH"
|
||||
|
||||
|
||||
set _OLD_VIRTUAL_PROMPT="$prompt"
|
||||
|
||||
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
|
||||
if ("install-soft-on-Astra-linux" != "") then
|
||||
set env_name = "install-soft-on-Astra-linux"
|
||||
else
|
||||
if (`basename "VIRTUAL_ENV"` == "__") then
|
||||
# special case for Aspen magic directories
|
||||
# see http://www.zetadev.com/software/aspen/
|
||||
set env_name = `basename \`dirname "$VIRTUAL_ENV"\``
|
||||
else
|
||||
set env_name = `basename "$VIRTUAL_ENV"`
|
||||
endif
|
||||
endif
|
||||
set prompt = "[$env_name] $prompt"
|
||||
unset env_name
|
||||
endif
|
||||
|
||||
alias pydoc python -m pydoc
|
||||
|
||||
rehash
|
|
@ -0,0 +1,75 @@
|
|||
# This file must be used with ". bin/activate.fish" *from fish* (http://fishshell.org)
|
||||
# you cannot run it directly
|
||||
|
||||
function deactivate -d "Exit virtualenv and return to normal shell environment"
|
||||
# reset old environment variables
|
||||
if test -n "$_OLD_VIRTUAL_PATH"
|
||||
set -gx PATH $_OLD_VIRTUAL_PATH
|
||||
set -e _OLD_VIRTUAL_PATH
|
||||
end
|
||||
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
|
||||
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
|
||||
set -e _OLD_VIRTUAL_PYTHONHOME
|
||||
end
|
||||
|
||||
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
|
||||
functions -e fish_prompt
|
||||
set -e _OLD_FISH_PROMPT_OVERRIDE
|
||||
functions -c _old_fish_prompt fish_prompt
|
||||
functions -e _old_fish_prompt
|
||||
end
|
||||
|
||||
set -e VIRTUAL_ENV
|
||||
if test "$argv[1]" != "nondestructive"
|
||||
# Self destruct!
|
||||
functions -e deactivate
|
||||
end
|
||||
end
|
||||
|
||||
# unset irrelevant variables
|
||||
deactivate nondestructive
|
||||
|
||||
set -gx VIRTUAL_ENV "/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux"
|
||||
|
||||
set -gx _OLD_VIRTUAL_PATH $PATH
|
||||
set -gx PATH "$VIRTUAL_ENV/bin" $PATH
|
||||
|
||||
# unset PYTHONHOME if set
|
||||
if set -q PYTHONHOME
|
||||
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
|
||||
set -e PYTHONHOME
|
||||
end
|
||||
|
||||
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
|
||||
# fish uses a function instead of an env var to generate the prompt.
|
||||
|
||||
# save the current fish_prompt function as the function _old_fish_prompt
|
||||
functions -c fish_prompt _old_fish_prompt
|
||||
|
||||
# with the original prompt function renamed, we can override with our own.
|
||||
function fish_prompt
|
||||
# Save the return status of the last command
|
||||
set -l old_status $status
|
||||
|
||||
# Prompt override?
|
||||
if test -n "(install-soft-on-Astra-linux) "
|
||||
printf "%s%s" "(install-soft-on-Astra-linux) " (set_color normal)
|
||||
else
|
||||
# ...Otherwise, prepend env
|
||||
set -l _checkbase (basename "$VIRTUAL_ENV")
|
||||
if test $_checkbase = "__"
|
||||
# special case for Aspen magic directories
|
||||
# see http://www.zetadev.com/software/aspen/
|
||||
printf "%s[%s]%s " (set_color -b blue white) (basename (dirname "$VIRTUAL_ENV")) (set_color normal)
|
||||
else
|
||||
printf "%s(%s)%s" (set_color -b blue white) (basename "$VIRTUAL_ENV") (set_color normal)
|
||||
end
|
||||
end
|
||||
|
||||
# Restore the return status of the previous command.
|
||||
echo "exit $old_status" | .
|
||||
_old_fish_prompt
|
||||
end
|
||||
|
||||
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
|
||||
end
|
|
@ -0,0 +1,11 @@
|
|||
#!/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux/bin/python3.7
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
|
||||
from setuptools.command.easy_install import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
|
@ -0,0 +1,11 @@
|
|||
#!/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux/bin/python3
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
|
||||
from setuptools.command.easy_install import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
|
@ -0,0 +1,11 @@
|
|||
#!/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux/bin/python3.7
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
|
||||
from setuptools.command.easy_install import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
|
@ -0,0 +1,11 @@
|
|||
#!/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux/bin/python3.7
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
|
||||
from pip._internal import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
|
@ -0,0 +1,11 @@
|
|||
#!/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux/bin/python3.7
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
|
||||
from pip._internal import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
|
@ -0,0 +1,11 @@
|
|||
#!/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux/bin/python3
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
|
||||
from pip._internal import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
|
@ -0,0 +1,11 @@
|
|||
#!/home/admincsm/Projects/GIT-Python-Astra/install-soft-on-Astra-linux/install-soft-on-Astra-linux/bin/python3.7
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
import sys
|
||||
|
||||
from pip._internal import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(main())
|
|
@ -0,0 +1 @@
|
|||
python3
|
|
@ -0,0 +1 @@
|
|||
/usr/bin/python3
|
|
@ -0,0 +1 @@
|
|||
/usr/bin/python3.7
|
Binary file not shown.
|
@ -0,0 +1,5 @@
|
|||
"""Run the EasyInstall command"""
|
||||
|
||||
if __name__ == '__main__':
|
||||
from setuptools.command.easy_install import main
|
||||
main()
|
|
@ -0,0 +1,165 @@
|
|||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
_clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -0,0 +1 @@
|
|||
pip
|
|
@ -0,0 +1,13 @@
|
|||
This program 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.
|
||||
|
||||
This program 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 this program in the COPYING and COPYING.LESSER files.
|
||||
If not, see <http://www.gnu.org/licenses/>.
|
|
@ -0,0 +1,165 @@
|
|||
Metadata-Version: 2.1
|
||||
Name: ldap3
|
||||
Version: 2.9.1
|
||||
Summary: A strictly RFC 4510 conforming LDAP V3 pure Python client library
|
||||
Home-page: https://github.com/cannatag/ldap3
|
||||
Author: Giovanni Cannata
|
||||
Author-email: cannatag@gmail.com
|
||||
License: LGPL v3
|
||||
Keywords: python3 python2 ldap
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Intended Audience :: System Administrators
|
||||
Classifier: Operating System :: MacOS :: MacOS X
|
||||
Classifier: Operating System :: Microsoft :: Windows
|
||||
Classifier: Operating System :: POSIX :: Linux
|
||||
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 2
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP
|
||||
Requires-Dist: pyasn1 (>=0.4.6)
|
||||
|
||||
LDAP3
|
||||
=====
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/ldap3.svg
|
||||
:target: https://pypi.python.org/pypi/ldap3/
|
||||
:alt: Latest Version
|
||||
|
||||
.. image:: https://img.shields.io/pypi/l/ldap3.svg
|
||||
:target: https://pypi.python.org/pypi/ldap3/
|
||||
:alt: License
|
||||
|
||||
.. image:: https://img.shields.io/travis/cannatag/ldap3/master.svg
|
||||
:target: https://travis-ci.org/cannatag/ldap3
|
||||
:alt: TRAVIS-CI build status for master branch
|
||||
|
||||
|
||||
ldap3 is a strictly RFC 4510 conforming **LDAP V3 pure Python client** library. The same codebase runs in Python 2, Python 3, PyPy and PyPy3.
|
||||
|
||||
|
||||
A more pythonic LDAP
|
||||
--------------------
|
||||
|
||||
LDAP operations look clumsy and hard-to-use because they reflect the old-age idea that time-consuming operations should be performed client-side
|
||||
to not hog the server with heavy elaborations. To alleviate this ldap3 includes a fully functional **Abstraction Layer** that lets you
|
||||
interact with the LDAP server in a modern and *pythonic* way. With the Abstraction Layer you don't need to directly issue any LDAP operation at all.
|
||||
|
||||
|
||||
Thread safe strategies
|
||||
----------------------
|
||||
|
||||
In multithreaded programs you must use on of **SAFE_SYNC** (synchronous connection strategy), **SAFE_RESTARTABLE** (restartable syncronous connection strategy) or **ASYNC** (asynchronous connection strategy).
|
||||
Each LDAP operation with SAFE_SYNC or SAFE_RESTARTABLE strategies returns a tuple of four elements: status, result, response and request.
|
||||
|
||||
* status: states if the operation was successful
|
||||
|
||||
* result: the LDAP result of the operation
|
||||
|
||||
* response: the response of a LDAP Search Operation
|
||||
|
||||
* request: the original request of the operation
|
||||
|
||||
The SafeSync strategy can be used with the Abstract Layer, but the Abstract Layer currently is NOT thread safe.
|
||||
For example, to use *SAFE_SYNC*::
|
||||
|
||||
from ldap3 import Server, Connection, SAFE_SYNC
|
||||
server = Server('my_server')
|
||||
conn = Connection(server, 'my_user', 'my_password', client_strategy=SAFE_SYNC, auto_bind=True)
|
||||
status, result, response, _ = conn.search('o=test', '(objectclass=*)') # usually you don't need the original request (4th element of the returned tuple)
|
||||
|
||||
|
||||
With *ASYNC* you must request the response with the *get_response()* method.
|
||||
|
||||
Home Page
|
||||
---------
|
||||
|
||||
The home page of the ldap3 project is https://github.com/cannatag/ldap3
|
||||
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
|
||||
Documentation is available at http://ldap3.readthedocs.io
|
||||
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
The ldap3 project is open source software released under the **LGPL v3 license**.
|
||||
Copyright 2013 - 2020 Giovanni Cannata
|
||||
|
||||
|
||||
PEP8 Compliance
|
||||
---------------
|
||||
|
||||
ldap3 is PEP8 compliant, except for line length.
|
||||
|
||||
|
||||
Download
|
||||
--------
|
||||
|
||||
Package download is available at https://pypi.python.org/pypi/ldap3.
|
||||
|
||||
|
||||
Install
|
||||
-------
|
||||
|
||||
Install with **pip install ldap3**
|
||||
|
||||
|
||||
Git repository
|
||||
--------------
|
||||
|
||||
You can download the latest source at https://github.com/cannatag/ldap3
|
||||
|
||||
|
||||
Continuous integration
|
||||
----------------------
|
||||
|
||||
Continuous integration for testing is at https://travis-ci.org/cannatag/ldap3
|
||||
|
||||
|
||||
Support & Development
|
||||
---------------------
|
||||
|
||||
You can submit support tickets on https://github.com/cannatag/ldap3/issues/new
|
||||
You can submit pull request on the **dev** branch at https://github.com/cannatag/ldap3/tree/dev
|
||||
|
||||
|
||||
Thanks to
|
||||
---------
|
||||
|
||||
* **Ilya Etingof**, the author of the *pyasn1* package for his excellent work and support.
|
||||
|
||||
* **Mark Lutz** for his *Learning Python* and *Programming Python* excellent books series and **John Goerzen** and **Brandon Rhodes** for their book *Foundations of Python Network Programming*. These books are wonderful tools for learning Python and this project owes a lot to them.
|
||||
|
||||
* **JetBrains** for donating to this project the Open Source license of *PyCharm Professional*.
|
||||
|
||||
* **GitHub** for providing the *free source repository space and the tools* I use to develop this project.
|
||||
|
||||
* The **FreeIPA** team for letting me use their demo LDAP server in the ldap3 tutorial.
|
||||
|
||||
|
||||
Contact me
|
||||
----------
|
||||
|
||||
For information and suggestions you can contact me at cannatag@gmail.com. You can also open a support ticket on https://github.com/cannatag/ldap3/issues/new
|
||||
|
||||
|
||||
Donate
|
||||
------
|
||||
|
||||
If you want to keep this project up and running you can send me an Amazon gift card. I will use it to improve my skills in Information and Communication technologies.
|
||||
|
||||
|
||||
Changelog
|
||||
---------
|
||||
|
||||
Updated changelog at https://ldap3.readthedocs.io/changelog.html
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,230 @@
|
|||
ldap3-2.9.1.dist-info/COPYING.LESSER.txt,sha256=LPNKwDiu5awG-TPd0dqYJuC7k4PBPY4LCI_O0LSpW1s,7814
|
||||
ldap3-2.9.1.dist-info/COPYING.txt,sha256=mW-DoJmlCb8dVheH3WgTBXT6aRoPIPc8E4WnHWxpQtU,35820
|
||||
ldap3-2.9.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
ldap3-2.9.1.dist-info/LICENSE.txt,sha256=XX5XVJ8iam2PA7UJW3uo37L_x-X6eSIP5lo4VMdxWbA,683
|
||||
ldap3-2.9.1.dist-info/METADATA,sha256=SgBryFUSxtahPvaoldnKM2aVtoXdVh_D5CaaOpIXgMU,5408
|
||||
ldap3-2.9.1.dist-info/RECORD,,
|
||||
ldap3-2.9.1.dist-info/WHEEL,sha256=Z-nyYpwrcSqxfdux5Mbn_DQ525iP7J2DG3JgGvOYyTQ,110
|
||||
ldap3-2.9.1.dist-info/top_level.txt,sha256=Zg1GRSTgLedl2RfLDLI0W0OaUFdYc0H1zzRbrK96JBw,6
|
||||
ldap3/__init__.py,sha256=fDS0j-uC8aY5g6U2z98mYC8JM6xLEZmL1RTn3exUkuE,4333
|
||||
ldap3/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/__pycache__/version.cpython-35.pyc,,
|
||||
ldap3/abstract/__init__.py,sha256=mw1tDTTwjwK-KF67PDCxgVltT_UM3YLFJyJbz8swMxA,2166
|
||||
ldap3/abstract/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/abstract/__pycache__/attrDef.cpython-35.pyc,,
|
||||
ldap3/abstract/__pycache__/attribute.cpython-35.pyc,,
|
||||
ldap3/abstract/__pycache__/cursor.cpython-35.pyc,,
|
||||
ldap3/abstract/__pycache__/entry.cpython-35.pyc,,
|
||||
ldap3/abstract/__pycache__/objectDef.cpython-35.pyc,,
|
||||
ldap3/abstract/attrDef.py,sha256=Bw23WrEdkErJUTHBJe--ag1KRP7lDueB7XDhC9HuCvo,4983
|
||||
ldap3/abstract/attribute.py,sha256=w8S2uhznzygj_VStYH_NGCvosPD8k3gXAVuE87Pkwj4,12428
|
||||
ldap3/abstract/cursor.py,sha256=UMKVwBXzsLraAHDKQYzfJ6yIaNC_m8XzLr5CQEzX5Vk,43620
|
||||
ldap3/abstract/entry.py,sha256=XeKOH1UA0SU_dJaMVNHv2_AswoVo5L7ok0t6coznJGA,35603
|
||||
ldap3/abstract/objectDef.py,sha256=48ROgT4Q3C0asmo2iYFonB2B3qNrsCyeNg5cHgHTxqk,11809
|
||||
ldap3/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/core/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/connection.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/exceptions.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/pooling.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/rdns.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/results.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/server.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/timezone.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/tls.cpython-35.pyc,,
|
||||
ldap3/core/__pycache__/usage.cpython-35.pyc,,
|
||||
ldap3/core/connection.py,sha256=Fy26Xkv0ikFY05qUTtfDDJJieLvlHUsuKneNvJKk2Zg,82600
|
||||
ldap3/core/exceptions.py,sha256=jjyx8LCftsxoy4i_KrpcAUMW0rAwfu0UZnBBPwCYOrk,16670
|
||||
ldap3/core/pooling.py,sha256=KXfOKdYWaKLDe-bDZZdEhnJAVcPb5cRAc51XZFDNFtA,14881
|
||||
ldap3/core/rdns.py,sha256=GxK_0nw1F6-ep_uApxKOYSfwCkSsrjmPFUSWaPc3NUQ,2525
|
||||
ldap3/core/results.py,sha256=TtF3F4UR32nseJhEUHE40DJjnXVYdvjLwKDyBlv0Gdo,5564
|
||||
ldap3/core/server.py,sha256=wFWUsQOmNsylQ_Cp7hja6mRKwEdOKOM7rec3tWG6VSc,34112
|
||||
ldap3/core/timezone.py,sha256=URXtnURG_WpbBwgJNe5YGeQryXD9NDO9yTfenGDLQm4,1620
|
||||
ldap3/core/tls.py,sha256=iO8a3SOogZ3n01Yn_i-und3hg6dqLq1ciaUycJy-yYk,15389
|
||||
ldap3/core/usage.py,sha256=sXRrE6S5shv-RrjL9yjz5H77voXHnbparHuAYdslOWo,10690
|
||||
ldap3/extend/__init__.py,sha256=yRQfHDmqJ2CiZlF5y2mLQtO2Mna-4NnwWlw7ABUkZFk,14146
|
||||
ldap3/extend/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/extend/__pycache__/operation.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/extend/microsoft/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/__pycache__/addMembersToGroups.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/__pycache__/dirSync.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/__pycache__/modifyPassword.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/__pycache__/persistentSearch.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/__pycache__/removeMembersFromGroups.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/__pycache__/unlockAccount.cpython-35.pyc,,
|
||||
ldap3/extend/microsoft/addMembersToGroups.py,sha256=Xktg2W-lyL-2AvNfgwQ67yI_Kd5mLN56JvptfbDFk9g,4220
|
||||
ldap3/extend/microsoft/dirSync.py,sha256=XKl1o8_JeVPiBAWQX19po4zQ5ET34AtR_Ncg1fBASwU,4238
|
||||
ldap3/extend/microsoft/modifyPassword.py,sha256=DTdm6w7x__-jfSsBrQDNF4ptWk8kZi7hLW6mWTNRAxc,3160
|
||||
ldap3/extend/microsoft/persistentSearch.py,sha256=EboAmUIeGkq_x0FsZUHUKqtjkbayRVTKNEnyL-1x8yo,4303
|
||||
ldap3/extend/microsoft/removeMembersFromGroups.py,sha256=IByzrBU5Buhb_EjRJgkAJE2eiLObKhWuR2gla8q38Jc,4112
|
||||
ldap3/extend/microsoft/unlockAccount.py,sha256=wYCae0gBhqZNloO_b5Dzey8DHHjZYruJdO3WaRFrMHs,2142
|
||||
ldap3/extend/novell/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/extend/novell/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/addMembersToGroups.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/checkGroupsMemberships.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/endTransaction.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/getBindDn.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/listReplicas.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/nmasGetUniversalPassword.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/nmasSetUniversalPassword.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/partition_entry_count.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/removeMembersFromGroups.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/replicaInfo.cpython-35.pyc,,
|
||||
ldap3/extend/novell/__pycache__/startTransaction.cpython-35.pyc,,
|
||||
ldap3/extend/novell/addMembersToGroups.py,sha256=zKzjpgIsiB4AyhPxbS54kcA3IukUdmH00VKPbXrlZ8g,8209
|
||||
ldap3/extend/novell/checkGroupsMemberships.py,sha256=UpcDbMlDFitpUX3piTNijM9MVg4OgMI18nyYpaH7Dzw,8006
|
||||
ldap3/extend/novell/endTransaction.py,sha256=FJ_Fh5x4kSP8qnvHU8YWnDZHoj0GjRN8KLHslP-DWCs,2252
|
||||
ldap3/extend/novell/getBindDn.py,sha256=FmObH2gATugZHMqYFyvvV1zugqaI6SRylkblddp_TkI,1422
|
||||
ldap3/extend/novell/listReplicas.py,sha256=yHDgw0S3utZQaRehZxWsIGSONhvgKgDby5he4Qku4Qk,1851
|
||||
ldap3/extend/novell/nmasGetUniversalPassword.py,sha256=C3kBWt80qBox6anBULlnvzQB50NlENmWcLt5ttiROSU,2225
|
||||
ldap3/extend/novell/nmasSetUniversalPassword.py,sha256=n5X-P_8R9uiQWPhm4wzOnP0_Z63JTSgDDkL-uKbqYRE,2077
|
||||
ldap3/extend/novell/partition_entry_count.py,sha256=aoLUTylSGlDfKARQxTSwt0yokCgRjx-1Vz2JPIPR3Zo,2077
|
||||
ldap3/extend/novell/removeMembersFromGroups.py,sha256=Tadzd3iXhEYZ-M-v5SfapDpZ3xjVNcHUOWaY1G3lIHI,8299
|
||||
ldap3/extend/novell/replicaInfo.py,sha256=a315GB4ZEM_svqc252KTVijMX_W84gKId6sHx_hFhy0,3391
|
||||
ldap3/extend/novell/startTransaction.py,sha256=h1YeBByo2zC7UmLdhbX6L4pJ3ajTIdABvoRp-b6FyDg,2293
|
||||
ldap3/extend/operation.py,sha256=rm6hcH0JXiKHvlpQmaCZ-8Rw279bgff-268dw6hCZXo,3988
|
||||
ldap3/extend/standard/PagedSearch.py,sha256=QyORR5GTMcPvd5E7qMKmbBmi5K7HLHzaGiTsXUhpNhk,6385
|
||||
ldap3/extend/standard/PersistentSearch.py,sha256=5Dvlix29nsbMl0B7sm0dBoCOZFN4w58dhY5C-dsrbhU,5367
|
||||
ldap3/extend/standard/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/extend/standard/__pycache__/PagedSearch.cpython-35.pyc,,
|
||||
ldap3/extend/standard/__pycache__/PersistentSearch.cpython-35.pyc,,
|
||||
ldap3/extend/standard/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/extend/standard/__pycache__/modifyPassword.cpython-35.pyc,,
|
||||
ldap3/extend/standard/__pycache__/whoAmI.cpython-35.pyc,,
|
||||
ldap3/extend/standard/modifyPassword.py,sha256=unNRVqGMlyqohN3s1chgqmKFZNkX1MpKGJ2V1aC5f_U,3512
|
||||
ldap3/extend/standard/whoAmI.py,sha256=1lQK1wmfNzAgD7fNBJCCafrrLY4wK8U2vz2ERNQBUkg,1389
|
||||
ldap3/operation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/operation/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/abandon.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/add.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/bind.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/compare.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/delete.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/extended.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/modify.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/modifyDn.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/search.cpython-35.pyc,,
|
||||
ldap3/operation/__pycache__/unbind.cpython-35.pyc,,
|
||||
ldap3/operation/abandon.py,sha256=Mf5a4-UTdnHF-E9VWFvy98V4XkrvvydIt0wszVrjgd8,1139
|
||||
ldap3/operation/add.py,sha256=4XXYwAnKbVfS8IDe8mC1fzG9NPCYNpEl4y9t4FeSWls,2983
|
||||
ldap3/operation/bind.py,sha256=70pPGIUeLQUi7Y3t7PbODykHBKViKXDVsP0c4S7Ykwg,7802
|
||||
ldap3/operation/compare.py,sha256=1mvmuI_uJUh3-dVym6VkTjC9rVxBFYShQQthc-nwxjI,2467
|
||||
ldap3/operation/delete.py,sha256=_SF5tgIIUZP_q0RG2WIaUuZx9tK8C2mHYpHTa-fim3s,1527
|
||||
ldap3/operation/extended.py,sha256=EB47JGHjbgjAQEFaQcsG2PaLvvgK4sXYJXKKUj2_8Hs,4914
|
||||
ldap3/operation/modify.py,sha256=N8w-CD4i9-9AXB8lR7ZazXoa3NAMQCQgdmdaEHlFa1Y,3927
|
||||
ldap3/operation/modifyDn.py,sha256=ut5sY8sP_UTDCDq73Ct0Y8awk73qDJ0MHWghj3enCIQ,2358
|
||||
ldap3/operation/search.py,sha256=RjaA4_HxnMQeuE9pSWzL9bzy07fDPkOaCppyio13xi4,28197
|
||||
ldap3/operation/unbind.py,sha256=Ph5ww3NkEz8yX7dv4FC5zikJLUfya4otOlvFu_In9y4,1012
|
||||
ldap3/protocol/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/protocol/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/controls.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/convert.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/microsoft.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/novell.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/oid.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/persistentSearch.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/rfc2696.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/rfc2849.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/rfc3062.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/rfc4511.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/rfc4512.cpython-35.pyc,,
|
||||
ldap3/protocol/__pycache__/rfc4527.cpython-35.pyc,,
|
||||
ldap3/protocol/controls.py,sha256=pty1PqVDiRB71jPPMbgiPpcjRbBTJRtP3_VRkbOPsXA,1392
|
||||
ldap3/protocol/convert.py,sha256=sQWsEfffAqRbKXEevL_zCDEGpQ6z_un1w_X40D-ZlJQ,9879
|
||||
ldap3/protocol/formatters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/protocol/formatters/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/protocol/formatters/__pycache__/formatters.cpython-35.pyc,,
|
||||
ldap3/protocol/formatters/__pycache__/standard.cpython-35.pyc,,
|
||||
ldap3/protocol/formatters/__pycache__/validators.cpython-35.pyc,,
|
||||
ldap3/protocol/formatters/formatters.py,sha256=QNiIBtMbFh9X_mv0skKfeQcJ3xAEMpox5QWZWQ1VfyE,16175
|
||||
ldap3/protocol/formatters/standard.py,sha256=V0Gf9e80v2ALJbh6g6lc7iB4b1QOqQpGU64Kvjxxn9Y,15252
|
||||
ldap3/protocol/formatters/validators.py,sha256=XQunpPTqDESJVS_DR8gKR53U9-wsTtHw2GXOEEXY5RA,19777
|
||||
ldap3/protocol/microsoft.py,sha256=RPk9FxPYzMT9yvsV1hNnfQbCylydPM-G0g-g4t8aOMc,5416
|
||||
ldap3/protocol/novell.py,sha256=7yyZ2oFUuNlJ3pBawEhRkolTt_tTnvdPfGgXXcRwnlY,5157
|
||||
ldap3/protocol/oid.py,sha256=Y6BsJGLi9p8ncWgY46NAp4SChkZChvk_tNHibjf69Bs,127654
|
||||
ldap3/protocol/persistentSearch.py,sha256=3mNW7KFu57uLJmKZB3E26BMvuuyAbDMrIp5arJrKZ4s,3177
|
||||
ldap3/protocol/rfc2696.py,sha256=UY6UUYaG_qE1llceZFLYjkW5RyXrIhTGeYI9W2xVqEg,2267
|
||||
ldap3/protocol/rfc2849.py,sha256=E6otnGh4e3jU8Tzsftt1xQS95nwCeeNk_vgr6UkAe3M,11234
|
||||
ldap3/protocol/rfc3062.py,sha256=zxnQ3eP94PrL8Vy8HUD7umH9nXkJMHjEMrSEinJi7-E,2955
|
||||
ldap3/protocol/rfc4511.py,sha256=7QUoXYeKdtts7p7crxeeZduGAlk3HBWgun03SLKhMf4,42545
|
||||
ldap3/protocol/rfc4512.py,sha256=x6VQsUgOo3nUwN1x7A_aHOvWonqc1N3dOpghSm7IRMo,39009
|
||||
ldap3/protocol/rfc4527.py,sha256=piYI1zm1jJ-Wp65_t5QRGdvXv6gbYum7hmstNJSk344,2078
|
||||
ldap3/protocol/sasl/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/protocol/sasl/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/protocol/sasl/__pycache__/digestMd5.cpython-35.pyc,,
|
||||
ldap3/protocol/sasl/__pycache__/external.cpython-35.pyc,,
|
||||
ldap3/protocol/sasl/__pycache__/kerberos.cpython-35.pyc,,
|
||||
ldap3/protocol/sasl/__pycache__/plain.cpython-35.pyc,,
|
||||
ldap3/protocol/sasl/__pycache__/sasl.cpython-35.pyc,,
|
||||
ldap3/protocol/sasl/digestMd5.py,sha256=y58cRTmAAVhrtBAWMCR1VsHR1qZLzUVGmJwyzdM2xrM,5829
|
||||
ldap3/protocol/sasl/external.py,sha256=rXeZI70yZQWrr_j0COysZURKWCVQ22pjMdyRj46mQpo,1051
|
||||
ldap3/protocol/sasl/kerberos.py,sha256=4ggxFknqHKwjgkB3I2vjFS9qNtTUhXyMAJ4yVdq3tZA,15290
|
||||
ldap3/protocol/sasl/plain.py,sha256=uwuoh6Z1P6U4fhyvKEXNjcPyhY2r-COewVjPlIWLK-g,2235
|
||||
ldap3/protocol/sasl/sasl.py,sha256=-iHpfJVO1tf1NhK5iM69Xcw7uJsGjFGi5ftUhPBVyxA,7309
|
||||
ldap3/protocol/schemas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/protocol/schemas/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/protocol/schemas/__pycache__/ad2012R2.cpython-35.pyc,,
|
||||
ldap3/protocol/schemas/__pycache__/ds389.cpython-35.pyc,,
|
||||
ldap3/protocol/schemas/__pycache__/edir888.cpython-35.pyc,,
|
||||
ldap3/protocol/schemas/__pycache__/edir914.cpython-35.pyc,,
|
||||
ldap3/protocol/schemas/__pycache__/slapd24.cpython-35.pyc,,
|
||||
ldap3/protocol/schemas/ad2012R2.py,sha256=ZhjzvBlnxbk4Xmh2a-yiwHdQYGs27N5cC7eeeasKlwM,333672
|
||||
ldap3/protocol/schemas/ds389.py,sha256=_vsGT8rTaMDX1h_aod1iL7hhvI12blFi3YqmWVHgj50,310500
|
||||
ldap3/protocol/schemas/edir888.py,sha256=2C-QL5KJYEHm7A-UAVSN0PJSNRkPX4A1OOOHWVBQwRw,177862
|
||||
ldap3/protocol/schemas/edir914.py,sha256=O0VcJUmSRxUy8GKoNR1Cuhipij1R3o7hKeFuwMJNqQI,182158
|
||||
ldap3/protocol/schemas/slapd24.py,sha256=uAPuP5GsEG01HFe0tAF0h10_C5iLDOtIvdprsMKUtsU,129245
|
||||
ldap3/strategy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/strategy/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/asyncStream.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/asynchronous.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/base.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/ldifProducer.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/mockAsync.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/mockBase.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/mockSync.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/restartable.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/reusable.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/safeRestartable.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/safeSync.cpython-35.pyc,,
|
||||
ldap3/strategy/__pycache__/sync.cpython-35.pyc,,
|
||||
ldap3/strategy/asyncStream.py,sha256=L-Jcb_FGWeuXLkMl-wVKHxlQZOFzzo4wthuPm6NwDzk,4578
|
||||
ldap3/strategy/asynchronous.py,sha256=s7FhaxizhCPiWU4Dfxnc_Xh7F8DyFW3ELajDifYBxHI,15247
|
||||
ldap3/strategy/base.py,sha256=48stBVEx9WP13etYE7uOQkDqnUB8iIzu5HSKjd90FVc,51995
|
||||
ldap3/strategy/ldifProducer.py,sha256=V1hdqCUbetGq6nHPa8xucYn0G3lglRTAnlc4rV1bor4,5715
|
||||
ldap3/strategy/mockAsync.py,sha256=rZEbmE4vxWgGxHjt7Tr76diB-C2Q9G_Sj5wjBZjv2Rw,10259
|
||||
ldap3/strategy/mockBase.py,sha256=zvVBdJ7S3F7_w03-FHoaL4reJXqqOgai23ZauF0K0P8,46685
|
||||
ldap3/strategy/mockSync.py,sha256=hYGif2UHypzX1a5TT4gPn855ZO5VQveCe6oEQ4amYck,7315
|
||||
ldap3/strategy/restartable.py,sha256=wuetnY_XvnQ6dBkdIyBwDlvGAj7aWcet7hVf0OFrYXI,13209
|
||||
ldap3/strategy/reusable.py,sha256=hydBw6IQlB3pdPsilMh2Gb60KXoAhev88N4wcMnIUrs,25459
|
||||
ldap3/strategy/safeRestartable.py,sha256=sb9X7t8KgihhfVO1sqyZncOsb18_RnpEa8ifDnSOlmw,1079
|
||||
ldap3/strategy/safeSync.py,sha256=bs034mamY73coENS3B8BIPtpaSdCY6rHR3Fd515HGCQ,1044
|
||||
ldap3/strategy/sync.py,sha256=feeQyySWkkp_8aijZ77n4MNCEglfRpj2Bsm9gTA9T5o,13932
|
||||
ldap3/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
ldap3/utils/__pycache__/__init__.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/asn1.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/ciDict.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/config.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/conv.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/dn.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/hashed.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/log.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/ntlm.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/ordDict.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/port_validators.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/repr.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/tls_backport.cpython-35.pyc,,
|
||||
ldap3/utils/__pycache__/uri.cpython-35.pyc,,
|
||||
ldap3/utils/asn1.py,sha256=FYZA1WCmnHWCIqDiyKx9QqRBK7lcNa7n4K-EiX_HbRU,9304
|
||||
ldap3/utils/ciDict.py,sha256=_X4k9lnqmJ8MP55CSO4ZSLmfWGXkFZHDtvtF1Z35aaQ,7893
|
||||
ldap3/utils/config.py,sha256=H8LzitQYyx1lJUycZa6jHlHVV5aIZ5JkwSUs5H_8xuU,14927
|
||||
ldap3/utils/conv.py,sha256=D-rhsIHaV152ZypCQvIqC7jccyKi6GHXERNKSwjk7EI,9741
|
||||
ldap3/utils/dn.py,sha256=vKB-BzIqxphfbtMkpr2s8sieosGcbghVblz0iPWCwKU,14441
|
||||
ldap3/utils/hashed.py,sha256=yhqSd9iLj2hsYqT1p9ZnBFQPaaB9pnkVrYb1H6dzFBA,3575
|
||||
ldap3/utils/log.py,sha256=ScJ5IS9zYuSWqXkP___KQ8mzdoGzocfMkMiTSG2870U,7252
|
||||
ldap3/utils/ntlm.py,sha256=XKoz2G8W4npLIyTjMDpqepb3Xjz10qH6HmBxilAsMy0,20125
|
||||
ldap3/utils/ordDict.py,sha256=mmMzSklrAxwRZprA1Lj5K1D-eD-HLWVHxQVQD0NiPnQ,4251
|
||||
ldap3/utils/port_validators.py,sha256=r23jlhWgU09Kq8X0TB4nUqHiO3iYNQ0kh4WMgcDoZzM,1396
|
||||
ldap3/utils/repr.py,sha256=vKhXotKmFD5sCYNUZOHV5ybR2LbSsjVeDtY0RCLFa5E,1700
|
||||
ldap3/utils/tls_backport.py,sha256=VC4irAJVmNnuTu3uccViLYJU7YL-OXsvVbQR3XJJh5c,5426
|
||||
ldap3/utils/uri.py,sha256=bGq6eNc063NSJOF9xYl3mqLnF1c-SqvUq3-rd4CdaEA,4795
|
||||
ldap3/version.py,sha256=QxpAi50y5ypa0THbj-RzN7f3GTCbWftJRbdWCGr9J4s,626
|
|
@ -0,0 +1,6 @@
|
|||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.36.2)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py2-none-any
|
||||
Tag: py3-none-any
|
||||
|
|
@ -0,0 +1 @@
|
|||
ldap3
|
|
@ -0,0 +1,150 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2013.05.15
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2013 - 2020 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 types import GeneratorType
|
||||
|
||||
# authentication
|
||||
ANONYMOUS = 'ANONYMOUS'
|
||||
SIMPLE = 'SIMPLE'
|
||||
SASL = 'SASL'
|
||||
NTLM = 'NTLM'
|
||||
|
||||
# SASL MECHANISMS
|
||||
EXTERNAL = 'EXTERNAL'
|
||||
DIGEST_MD5 = 'DIGEST-MD5'
|
||||
KERBEROS = GSSAPI = 'GSSAPI'
|
||||
PLAIN = 'PLAIN'
|
||||
|
||||
AUTO_BIND_DEFAULT = 'DEFAULT' # binds connection when using "with" context manager
|
||||
AUTO_BIND_NONE = 'NONE' # same as False, no bind is performed
|
||||
AUTO_BIND_NO_TLS = 'NO_TLS' # same as True, bind is performed without tls
|
||||
AUTO_BIND_TLS_BEFORE_BIND = 'TLS_BEFORE_BIND' # start_tls is performed before bind
|
||||
AUTO_BIND_TLS_AFTER_BIND = 'TLS_AFTER_BIND' # start_tls is performed after bind
|
||||
|
||||
# server IP dual stack mode
|
||||
IP_SYSTEM_DEFAULT = 'IP_SYSTEM_DEFAULT'
|
||||
IP_V4_ONLY = 'IP_V4_ONLY'
|
||||
IP_V6_ONLY = 'IP_V6_ONLY'
|
||||
IP_V4_PREFERRED = 'IP_V4_PREFERRED'
|
||||
IP_V6_PREFERRED = 'IP_V6_PREFERRED'
|
||||
|
||||
# search scope
|
||||
BASE = 'BASE'
|
||||
LEVEL = 'LEVEL'
|
||||
SUBTREE = 'SUBTREE'
|
||||
|
||||
# search alias
|
||||
DEREF_NEVER = 'NEVER'
|
||||
DEREF_SEARCH = 'SEARCH'
|
||||
DEREF_BASE = 'FINDING_BASE'
|
||||
DEREF_ALWAYS = 'ALWAYS'
|
||||
|
||||
# search attributes
|
||||
ALL_ATTRIBUTES = '*'
|
||||
NO_ATTRIBUTES = '1.1' # as per RFC 4511
|
||||
ALL_OPERATIONAL_ATTRIBUTES = '+' # as per RFC 3673
|
||||
|
||||
# modify type
|
||||
MODIFY_ADD = 'MODIFY_ADD'
|
||||
MODIFY_DELETE = 'MODIFY_DELETE'
|
||||
MODIFY_REPLACE = 'MODIFY_REPLACE'
|
||||
MODIFY_INCREMENT = 'MODIFY_INCREMENT'
|
||||
|
||||
# client strategies
|
||||
SYNC = 'SYNC'
|
||||
SAFE_SYNC = 'SAFE_SYNC'
|
||||
SAFE_RESTARTABLE = 'SAFE_RESTARTABLE'
|
||||
ASYNC = 'ASYNC'
|
||||
LDIF = 'LDIF'
|
||||
RESTARTABLE = 'RESTARTABLE'
|
||||
REUSABLE = 'REUSABLE'
|
||||
MOCK_SYNC = 'MOCK_SYNC'
|
||||
MOCK_ASYNC = 'MOCK_ASYNC'
|
||||
ASYNC_STREAM = 'ASYNC_STREAM'
|
||||
|
||||
# get rootDSE info
|
||||
NONE = 'NO_INFO'
|
||||
DSA = 'DSA'
|
||||
SCHEMA = 'SCHEMA'
|
||||
ALL = 'ALL'
|
||||
|
||||
OFFLINE_EDIR_8_8_8 = 'EDIR_8_8_8'
|
||||
OFFLINE_EDIR_9_1_4 = 'EDIR_9_1_4'
|
||||
OFFLINE_AD_2012_R2 = 'AD_2012_R2'
|
||||
OFFLINE_SLAPD_2_4 = 'SLAPD_2_4'
|
||||
OFFLINE_DS389_1_3_3 = 'DS389_1_3_3'
|
||||
|
||||
# server pooling
|
||||
FIRST = 'FIRST'
|
||||
ROUND_ROBIN = 'ROUND_ROBIN'
|
||||
RANDOM = 'RANDOM'
|
||||
|
||||
# Hashed password
|
||||
HASHED_NONE = 'PLAIN'
|
||||
HASHED_SHA = 'SHA'
|
||||
HASHED_SHA256 = 'SHA256'
|
||||
HASHED_SHA384 = 'SHA384'
|
||||
HASHED_SHA512 = 'SHA512'
|
||||
HASHED_MD5 = 'MD5'
|
||||
HASHED_SALTED_SHA = 'SALTED_SHA'
|
||||
HASHED_SALTED_SHA256 = 'SALTED_SHA256'
|
||||
HASHED_SALTED_SHA384 = 'SALTED_SHA384'
|
||||
HASHED_SALTED_SHA512 = 'SALTED_SHA512'
|
||||
HASHED_SALTED_MD5 = 'SALTED_MD5'
|
||||
|
||||
if str is not bytes: # Python 3
|
||||
NUMERIC_TYPES = (int, float)
|
||||
INTEGER_TYPES = (int, )
|
||||
else:
|
||||
NUMERIC_TYPES = (int, long, float)
|
||||
INTEGER_TYPES = (int, long)
|
||||
|
||||
# types for string and sequence
|
||||
if str is not bytes: # Python 3
|
||||
STRING_TYPES = (str, )
|
||||
SEQUENCE_TYPES = (set, list, tuple, GeneratorType, type(dict().keys())) # dict.keys() is a iterable memoryview in Python 3
|
||||
else: # Python 2
|
||||
try:
|
||||
from future.types.newstr import newstr
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
STRING_TYPES = (str, unicode)
|
||||
SEQUENCE_TYPES = (set, list, tuple, GeneratorType)
|
||||
|
||||
# centralized imports # must be at the end of the __init__.py file
|
||||
from .version import __author__, __version__, __email__, __description__, __status__, __license__, __url__
|
||||
from .utils.config import get_config_parameter, set_config_parameter
|
||||
from .core.server import Server
|
||||
from .core.connection import Connection
|
||||
from .core.tls import Tls
|
||||
from .core.pooling import ServerPool
|
||||
from .core.rdns import ReverseDnsSetting
|
||||
from .abstract.objectDef import ObjectDef
|
||||
from .abstract.attrDef import AttrDef
|
||||
from .abstract.attribute import Attribute, WritableAttribute, OperationalAttribute
|
||||
from .abstract.entry import Entry, WritableEntry
|
||||
from .abstract.cursor import Reader, Writer
|
||||
from .protocol.rfc4512 import DsaInfo, SchemaInfo
|
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,50 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.08.31
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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/>.
|
||||
|
||||
STATUS_INIT = 'Initialized' # The entry object is initialized
|
||||
STATUS_VIRTUAL = 'Virtual' # The entry is a new writable entry, still empty
|
||||
STATUS_MANDATORY_MISSING = 'Missing mandatory attributes' # The entry has some mandatory attributes missing
|
||||
STATUS_READ = 'Read' # The entry has been read
|
||||
STATUS_WRITABLE = 'Writable' # The entry has been made writable, still no changes
|
||||
STATUS_PENDING_CHANGES = 'Pending changes' # The entry has some changes to commit, mandatory attributes are present
|
||||
STATUS_COMMITTED = 'Committed' # The entry changes has been committed
|
||||
STATUS_READY_FOR_DELETION = 'Ready for deletion' # The entry is set to be deleted
|
||||
STATUS_READY_FOR_MOVING = 'Ready for moving' # The entry is set to be moved in the DIT
|
||||
STATUS_READY_FOR_RENAMING = 'Ready for renaming' # The entry is set to be renamed
|
||||
STATUS_DELETED = 'Deleted' # The entry has been deleted
|
||||
|
||||
STATUSES = [STATUS_INIT,
|
||||
STATUS_VIRTUAL,
|
||||
STATUS_MANDATORY_MISSING,
|
||||
STATUS_READ,
|
||||
STATUS_WRITABLE,
|
||||
STATUS_PENDING_CHANGES,
|
||||
STATUS_COMMITTED,
|
||||
STATUS_READY_FOR_DELETION,
|
||||
STATUS_READY_FOR_MOVING,
|
||||
STATUS_READY_FOR_RENAMING,
|
||||
STATUS_DELETED]
|
||||
|
||||
INITIAL_STATUSES = [STATUS_READ, STATUS_WRITABLE, STATUS_VIRTUAL]
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,121 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.01.11
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 os import linesep
|
||||
|
||||
from .. import SEQUENCE_TYPES
|
||||
from ..core.exceptions import LDAPKeyError
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED
|
||||
|
||||
|
||||
class AttrDef(object):
|
||||
"""Hold the definition of an attribute
|
||||
|
||||
:param name: the real attribute name
|
||||
:type name: string
|
||||
:param key: the friendly name to use in queries and when accessing the attribute, default to the real attribute name
|
||||
:type key: string
|
||||
:param validate: called to check if the value in the query is valid, the callable is called with the value parameter
|
||||
:type validate: callable
|
||||
:param pre_query: called to transform values returned by search
|
||||
:type pre_query: callable
|
||||
:param post_query: called to transform values returned by search
|
||||
:type post_query: callable
|
||||
:param default: value returned when the attribute is absent (defaults to NotImplemented to allow use of None as default)
|
||||
:type default: string, integer
|
||||
:param dereference_dn: reference to an ObjectDef instance. When the attribute value contains a dn it will be searched and substituted in the entry
|
||||
:type dereference_dn: ObjectDef
|
||||
:param description: custom attribute description
|
||||
:type description: string
|
||||
:param mandatory: specify if attribute is defined as mandatory in LDAP schema
|
||||
:type mandatory: boolean
|
||||
"""
|
||||
|
||||
def __init__(self, name, key=None, validate=None, pre_query=None, post_query=None, default=NotImplemented, dereference_dn=None, description=None, mandatory=False, single_value=None, alias=None):
|
||||
self.name = name
|
||||
self.key = ''.join(key.split()) if key else name # key set to name if not present
|
||||
self.validate = validate
|
||||
self.pre_query = pre_query
|
||||
self.post_query = post_query
|
||||
self.default = default
|
||||
self.dereference_dn = dereference_dn
|
||||
self.description = description
|
||||
self.mandatory = mandatory
|
||||
self.single_value = single_value
|
||||
self.oid_info = None
|
||||
if not alias:
|
||||
self.other_names = None
|
||||
elif isinstance(alias, SEQUENCE_TYPES): # multiple aliases
|
||||
self.\
|
||||
other_names = set(alias)
|
||||
else: # single alias
|
||||
self.other_names = set([alias]) # python 2 compatibility
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated AttrDef: <%r>', self)
|
||||
|
||||
def __repr__(self):
|
||||
r = 'ATTR: ' + ', '.join([self.key] + list(self.other_names)) if self.other_names else self.key
|
||||
r += '' if self.name == self.key else ' [' + self.name + ']'
|
||||
r += '' if self.default is NotImplemented else ' - default: ' + str(self.default)
|
||||
r += '' if self.mandatory is None else ' - mandatory: ' + str(self.mandatory)
|
||||
r += '' if self.single_value is None else ' - single_value: ' + str(self.single_value)
|
||||
r += '' if not self.dereference_dn else ' - dereference_dn: ' + str(self.dereference_dn)
|
||||
r += '' if not self.description else ' - description: ' + str(self.description)
|
||||
if self.oid_info:
|
||||
for line in str(self.oid_info).split(linesep):
|
||||
r += linesep + ' ' + line
|
||||
return r
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, AttrDef):
|
||||
return self.key == other.key
|
||||
|
||||
return False
|
||||
|
||||
def __lt__(self, other):
|
||||
if isinstance(other, AttrDef):
|
||||
return self.key < other.key
|
||||
|
||||
return False
|
||||
|
||||
def __hash__(self):
|
||||
if self.key:
|
||||
return hash(self.key)
|
||||
else:
|
||||
return id(self) # unique for each instance
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
if hasattr(self, 'key') and key == 'key': # key cannot be changed because is being used for __hash__
|
||||
error_message = 'key \'%s\' already set' % key
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPKeyError(error_message)
|
||||
else:
|
||||
object.__setattr__(self, key, value)
|
|
@ -0,0 +1,290 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.01.06
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 os import linesep
|
||||
|
||||
from .. import MODIFY_ADD, MODIFY_REPLACE, MODIFY_DELETE, SEQUENCE_TYPES
|
||||
from ..core.exceptions import LDAPCursorError
|
||||
from ..utils.repr import to_stdout_encoding
|
||||
from . import STATUS_PENDING_CHANGES, STATUS_VIRTUAL, STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
class Attribute(object):
|
||||
"""Attribute/values object, it includes the search result (after post_query transformation) of each attribute in an entry
|
||||
|
||||
Attribute object is read only
|
||||
|
||||
- values: contain the processed attribute values
|
||||
- raw_values': contain the unprocessed attribute values
|
||||
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, attr_def, entry, cursor):
|
||||
self.key = attr_def.key
|
||||
self.definition = attr_def
|
||||
self.values = []
|
||||
self.raw_values = []
|
||||
self.response = None
|
||||
self.entry = entry
|
||||
self.cursor = cursor
|
||||
other_names = [name for name in attr_def.oid_info.name if self.key.lower() != name.lower()] if attr_def.oid_info else None
|
||||
self.other_names = set(other_names) if other_names else None # self.other_names is None if there are no short names, else is a set of secondary names
|
||||
|
||||
def __repr__(self):
|
||||
if len(self.values) == 1:
|
||||
r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
|
||||
elif len(self.values) > 1:
|
||||
r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
|
||||
filler = ' ' * (len(self.key) + 6)
|
||||
for value in self.values[1:]:
|
||||
r += linesep + filler + to_stdout_encoding(value)
|
||||
else:
|
||||
r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding('<no value>')
|
||||
|
||||
return r
|
||||
|
||||
def __str__(self):
|
||||
if len(self.values) == 1:
|
||||
return to_stdout_encoding(self.values[0])
|
||||
else:
|
||||
return to_stdout_encoding(self.values)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.values)
|
||||
|
||||
def __iter__(self):
|
||||
return self.values.__iter__()
|
||||
|
||||
def __getitem__(self, item):
|
||||
return self.values[item]
|
||||
|
||||
def __getstate__(self):
|
||||
cpy = dict(self.__dict__)
|
||||
cpy['cursor'] = None
|
||||
return cpy
|
||||
|
||||
def __eq__(self, other):
|
||||
try:
|
||||
if self.value == other:
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
"""
|
||||
:return: The single value or a list of values of the attribute.
|
||||
"""
|
||||
if not self.values:
|
||||
return None
|
||||
|
||||
return self.values[0] if len(self.values) == 1 else self.values
|
||||
|
||||
|
||||
class OperationalAttribute(Attribute):
|
||||
"""Operational attribute/values object. Include the search result of an
|
||||
operational attribute in an entry
|
||||
|
||||
OperationalAttribute object is read only
|
||||
|
||||
- values: contains the processed attribute values
|
||||
- raw_values: contains the unprocessed attribute values
|
||||
|
||||
It may not have an AttrDef
|
||||
|
||||
"""
|
||||
|
||||
def __repr__(self):
|
||||
if len(self.values) == 1:
|
||||
r = to_stdout_encoding(self.key) + ' [OPERATIONAL]: ' + to_stdout_encoding(self.values[0])
|
||||
elif len(self.values) > 1:
|
||||
r = to_stdout_encoding(self.key) + ' [OPERATIONAL]: ' + to_stdout_encoding(self.values[0])
|
||||
filler = ' ' * (len(self.key) + 6)
|
||||
for value in sorted(self.values[1:]):
|
||||
r += linesep + filler + to_stdout_encoding(value)
|
||||
else:
|
||||
r = ''
|
||||
|
||||
return r
|
||||
|
||||
|
||||
class WritableAttribute(Attribute):
|
||||
def __repr__(self):
|
||||
filler = ' ' * (len(self.key) + 6)
|
||||
if len(self.values) == 1:
|
||||
r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
|
||||
elif len(self.values) > 1:
|
||||
r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
|
||||
for value in self.values[1:]:
|
||||
r += linesep + filler + to_stdout_encoding(value)
|
||||
else:
|
||||
r = to_stdout_encoding(self.key) + to_stdout_encoding(': <Virtual>')
|
||||
if self.definition.name in self.entry._changes:
|
||||
r += linesep + filler + 'CHANGES: ' + str(self.entry._changes[self.definition.name])
|
||||
return r
|
||||
|
||||
def __iadd__(self, other):
|
||||
self.add(other)
|
||||
return Ellipsis # hack to avoid calling set() in entry __setattr__
|
||||
|
||||
def __isub__(self, other):
|
||||
self.delete(other)
|
||||
return Ellipsis # hack to avoid calling set_value in entry __setattr__
|
||||
|
||||
def _update_changes(self, changes, remove_old=False):
|
||||
# checks for friendly key in AttrDef and uses the real attribute name
|
||||
if self.definition and self.definition.name:
|
||||
key = self.definition.name
|
||||
else:
|
||||
key = self.key
|
||||
|
||||
if key not in self.entry._changes or remove_old: # remove old changes (for removing attribute)
|
||||
self.entry._changes[key] = []
|
||||
|
||||
self.entry._changes[key].append(changes)
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'updated changes <%r> for <%s> attribute in <%s> entry', changes, self.key, self.entry.entry_dn)
|
||||
self.entry._state.set_status(STATUS_PENDING_CHANGES)
|
||||
|
||||
def add(self, values):
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'adding %r to <%s> attribute in <%s> entry', values, self.key, self.entry.entry_dn)
|
||||
# new value for attribute to commit with a MODIFY_ADD
|
||||
if self.entry._state._initial_status == STATUS_VIRTUAL:
|
||||
error_message = 'cannot perform a modify operation in a new entry'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
|
||||
error_message = self.entry.entry_status + ' - cannot add attributes'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if values is None:
|
||||
error_message = 'value to add cannot be None'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if values is not None:
|
||||
validated = self.definition.validate(values) # returns True, False or a value to substitute to the actual values
|
||||
if validated is False:
|
||||
error_message = 'value \'%s\' non valid for attribute \'%s\'' % (values, self.key)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
elif validated is not True: # a valid LDAP value equivalent to the actual values
|
||||
values = validated
|
||||
self._update_changes((MODIFY_ADD, values if isinstance(values, SEQUENCE_TYPES) else [values]))
|
||||
|
||||
def set(self, values):
|
||||
# new value for attribute to commit with a MODIFY_REPLACE, old values are deleted
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'setting %r to <%s> attribute in <%s> entry', values, self.key, self.entry.entry_dn)
|
||||
if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
|
||||
error_message = self.entry.entry_status + ' - cannot set attributes'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if values is None:
|
||||
error_message = 'new value cannot be None'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
validated = self.definition.validate(values) # returns True, False or a value to substitute to the actual values
|
||||
if validated is False:
|
||||
error_message = 'value \'%s\' non valid for attribute \'%s\'' % (values, self.key)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
elif validated is not True: # a valid LDAP value equivalent to the actual values
|
||||
values = validated
|
||||
self._update_changes((MODIFY_REPLACE, values if isinstance(values, SEQUENCE_TYPES) else [values]), remove_old=True)
|
||||
|
||||
def delete(self, values):
|
||||
# value for attribute to delete in commit with a MODIFY_DELETE
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'deleting %r from <%s> attribute in <%s> entry', values, self.key, self.entry.entry_dn)
|
||||
if self.entry._state._initial_status == STATUS_VIRTUAL:
|
||||
error_message = 'cannot delete an attribute value in a new entry'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
|
||||
error_message = self.entry.entry_status + ' - cannot delete attributes'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if values is None:
|
||||
error_message = 'value to delete cannot be None'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if not isinstance(values, SEQUENCE_TYPES):
|
||||
values = [values]
|
||||
for single_value in values:
|
||||
if single_value not in self.values:
|
||||
error_message = 'value \'%s\' not present in \'%s\'' % (single_value, ', '.join(self.values))
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
self._update_changes((MODIFY_DELETE, values))
|
||||
|
||||
def remove(self):
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'removing <%s> attribute in <%s> entry', self.key, self.entry.entry_dn)
|
||||
if self.entry._state._initial_status == STATUS_VIRTUAL:
|
||||
error_message = 'cannot remove an attribute in a new entry'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
|
||||
error_message = self.entry.entry_status + ' - cannot remove attributes'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
self._update_changes((MODIFY_REPLACE, []), True)
|
||||
|
||||
def discard(self):
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'discarding <%s> attribute in <%s> entry', self.key, self.entry.entry_dn)
|
||||
del self.entry._changes[self.key]
|
||||
if not self.entry._changes:
|
||||
self.entry._state.set_status(self.entry._state._initial_status)
|
||||
|
||||
@property
|
||||
def virtual(self):
|
||||
return False if len(self.values) else True
|
||||
|
||||
@property
|
||||
def changes(self):
|
||||
if self.key in self.entry._changes:
|
||||
return self.entry._changes[self.key]
|
||||
return None
|
|
@ -0,0 +1,912 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.01.06
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 collections import namedtuple
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from os import linesep
|
||||
from time import sleep
|
||||
|
||||
from . import STATUS_VIRTUAL, STATUS_READ, STATUS_WRITABLE
|
||||
from .. import SUBTREE, LEVEL, DEREF_ALWAYS, DEREF_NEVER, BASE, SEQUENCE_TYPES, STRING_TYPES, get_config_parameter
|
||||
from ..abstract import STATUS_PENDING_CHANGES
|
||||
from .attribute import Attribute, OperationalAttribute, WritableAttribute
|
||||
from .attrDef import AttrDef
|
||||
from .objectDef import ObjectDef
|
||||
from .entry import Entry, WritableEntry
|
||||
from ..core.exceptions import LDAPCursorError, LDAPObjectDereferenceError
|
||||
from ..core.results import RESULT_SUCCESS
|
||||
from ..utils.ciDict import CaseInsensitiveWithAliasDict
|
||||
from ..utils.dn import safe_dn, safe_rdn
|
||||
from ..utils.conv import to_raw
|
||||
from ..utils.config import get_config_parameter
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED
|
||||
from ..protocol.oid import ATTRIBUTE_DIRECTORY_OPERATION, ATTRIBUTE_DISTRIBUTED_OPERATION, ATTRIBUTE_DSA_OPERATION, CLASS_AUXILIARY
|
||||
|
||||
Operation = namedtuple('Operation', ('request', 'result', 'response'))
|
||||
|
||||
|
||||
def _ret_search_value(value):
|
||||
return value[0] + '=' + value[1:] if value[0] in '<>~' and value[1] != '=' else value
|
||||
|
||||
|
||||
def _create_query_dict(query_text):
|
||||
"""
|
||||
Create a dictionary with query key:value definitions
|
||||
query_text is a comma delimited key:value sequence
|
||||
"""
|
||||
query_dict = dict()
|
||||
if query_text:
|
||||
for arg_value_str in query_text.split(','):
|
||||
if ':' in arg_value_str:
|
||||
arg_value_list = arg_value_str.split(':')
|
||||
query_dict[arg_value_list[0].strip()] = arg_value_list[1].strip()
|
||||
|
||||
return query_dict
|
||||
|
||||
|
||||
class Cursor(object):
|
||||
# entry_class and attribute_class define the type of entry and attribute used by the cursor
|
||||
# entry_initial_status defines the initial status of a entry
|
||||
# entry_class = Entry, must be defined in subclasses
|
||||
# attribute_class = Attribute, must be defined in subclasses
|
||||
# entry_initial_status = STATUS, must be defined in subclasses
|
||||
|
||||
def __init__(self, connection, object_def, get_operational_attributes=False, attributes=None, controls=None, auxiliary_class=None):
|
||||
conf_attributes_excluded_from_object_def = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_OBJECT_DEF')]
|
||||
self.connection = connection
|
||||
self.get_operational_attributes = get_operational_attributes
|
||||
if connection._deferred_bind or connection._deferred_open: # probably a lazy connection, tries to bind
|
||||
connection._fire_deferred()
|
||||
|
||||
if isinstance(object_def, (STRING_TYPES, SEQUENCE_TYPES)):
|
||||
if connection.closed: # try to open connection if closed to read schema
|
||||
connection.bind()
|
||||
object_def = ObjectDef(object_def, connection.server.schema, auxiliary_class=auxiliary_class)
|
||||
self.definition = object_def
|
||||
if attributes: # checks if requested attributes are defined in ObjectDef
|
||||
not_defined_attributes = []
|
||||
if isinstance(attributes, STRING_TYPES):
|
||||
attributes = [attributes]
|
||||
|
||||
for attribute in attributes:
|
||||
if attribute not in self.definition._attributes and attribute.lower() not in conf_attributes_excluded_from_object_def:
|
||||
not_defined_attributes.append(attribute)
|
||||
|
||||
if not_defined_attributes:
|
||||
error_message = 'Attributes \'%s\' non in definition' % ', '.join(not_defined_attributes)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
|
||||
self.attributes = set(attributes) if attributes else set([attr.name for attr in self.definition])
|
||||
self.controls = controls
|
||||
self.execution_time = None
|
||||
self.entries = []
|
||||
self.schema = self.connection.server.schema
|
||||
self._do_not_reset = False # used for refreshing entry in entry_refresh() without removing all entries from the Cursor
|
||||
self._operation_history = list() # a list storing all the requests, results and responses for the last cursor operation
|
||||
|
||||
def __repr__(self):
|
||||
r = 'CURSOR : ' + self.__class__.__name__ + linesep
|
||||
r += 'CONN : ' + str(self.connection) + linesep
|
||||
r += 'DEFS : ' + ', '.join(self.definition._object_class)
|
||||
if self.definition._auxiliary_class:
|
||||
r += ' [AUX: ' + ', '.join(self.definition._auxiliary_class) + ']'
|
||||
r += linesep
|
||||
# for attr_def in sorted(self.definition):
|
||||
# r += (attr_def.key if attr_def.key == attr_def.name else (attr_def.key + ' <' + attr_def.name + '>')) + ', '
|
||||
# if r[-2] == ',':
|
||||
# r = r[:-2]
|
||||
# r += ']' + linesep
|
||||
if hasattr(self, 'attributes'):
|
||||
r += 'ATTRS : ' + repr(sorted(self.attributes)) + (' [OPERATIONAL]' if self.get_operational_attributes else '') + linesep
|
||||
if isinstance(self, Reader):
|
||||
if hasattr(self, 'base'):
|
||||
r += 'BASE : ' + repr(self.base) + (' [SUB]' if self.sub_tree else ' [LEVEL]') + linesep
|
||||
if hasattr(self, '_query') and self._query:
|
||||
r += 'QUERY : ' + repr(self._query) + ('' if '(' in self._query else (' [AND]' if self.components_in_and else ' [OR]')) + linesep
|
||||
if hasattr(self, 'validated_query') and self.validated_query:
|
||||
r += 'PARSED : ' + repr(self.validated_query) + ('' if '(' in self._query else (' [AND]' if self.components_in_and else ' [OR]')) + linesep
|
||||
if hasattr(self, 'query_filter') and self.query_filter:
|
||||
r += 'FILTER : ' + repr(self.query_filter) + linesep
|
||||
|
||||
if hasattr(self, 'execution_time') and self.execution_time:
|
||||
r += 'ENTRIES: ' + str(len(self.entries))
|
||||
r += ' [executed at: ' + str(self.execution_time.isoformat()) + ']' + linesep
|
||||
|
||||
if self.failed:
|
||||
r += 'LAST OPERATION FAILED [' + str(len(self.errors)) + ' failure' + ('s' if len(self.errors) > 1 else '') + ' at operation' + ('s ' if len(self.errors) > 1 else ' ') + ', '.join([str(i) for i, error in enumerate(self.operations) if error.result['result'] != RESULT_SUCCESS]) + ']'
|
||||
|
||||
return r
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
def __iter__(self):
|
||||
return self.entries.__iter__()
|
||||
|
||||
def __getitem__(self, item):
|
||||
"""Return indexed item, if index is not found then try to sequentially search in DN of entries.
|
||||
If only one entry is found return it else raise a KeyError exception. The exception message
|
||||
includes the number of entries that matches, if less than 10 entries match then show the DNs
|
||||
in the exception message.
|
||||
"""
|
||||
try:
|
||||
return self.entries[item]
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
if isinstance(item, STRING_TYPES):
|
||||
found = self.match_dn(item)
|
||||
|
||||
if len(found) == 1:
|
||||
return found[0]
|
||||
elif len(found) > 1:
|
||||
error_message = 'Multiple entries found: %d entries match the text in dn' % len(found) + ('' if len(found) > 10 else (' [' + '; '.join([e.entry_dn for e in found]) + ']'))
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise KeyError(error_message)
|
||||
|
||||
error_message = 'no entry found'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise KeyError(error_message)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.entries)
|
||||
|
||||
if str is not bytes: # Python 3
|
||||
def __bool__(self): # needed to make the cursor appears as existing in "if cursor:" even if there are no entries
|
||||
return True
|
||||
else: # Python 2
|
||||
def __nonzero__(self):
|
||||
return True
|
||||
|
||||
def _get_attributes(self, response, attr_defs, entry):
|
||||
"""Assign the result of the LDAP query to the Entry object dictionary.
|
||||
|
||||
If the optional 'post_query' callable is present in the AttrDef it is called with each value of the attribute and the callable result is stored in the attribute.
|
||||
|
||||
Returns the default value for missing attributes.
|
||||
If the 'dereference_dn' in AttrDef is a ObjectDef then the attribute values are treated as distinguished name and the relevant entry is retrieved and stored in the attribute value.
|
||||
|
||||
"""
|
||||
conf_operational_attribute_prefix = get_config_parameter('ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX')
|
||||
conf_attributes_excluded_from_object_def = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_OBJECT_DEF')]
|
||||
attributes = CaseInsensitiveWithAliasDict()
|
||||
used_attribute_names = set()
|
||||
for attr in attr_defs:
|
||||
attr_def = attr_defs[attr]
|
||||
attribute_name = None
|
||||
for attr_name in response['attributes']:
|
||||
if attr_def.name.lower() == attr_name.lower():
|
||||
attribute_name = attr_name
|
||||
break
|
||||
|
||||
if attribute_name or attr_def.default is not NotImplemented: # attribute value found in result or default value present - NotImplemented allows use of None as default
|
||||
attribute = self.attribute_class(attr_def, entry, self)
|
||||
attribute.response = response
|
||||
attribute.raw_values = response['raw_attributes'][attribute_name] if attribute_name else None
|
||||
if attr_def.post_query and attr_def.name in response['attributes'] and response['raw_attributes'] != list():
|
||||
attribute.values = attr_def.post_query(attr_def.key, response['attributes'][attribute_name])
|
||||
else:
|
||||
if attr_def.default is NotImplemented or (attribute_name and response['raw_attributes'][attribute_name] != list()):
|
||||
attribute.values = response['attributes'][attribute_name]
|
||||
else:
|
||||
attribute.values = attr_def.default if isinstance(attr_def.default, SEQUENCE_TYPES) else [attr_def.default]
|
||||
if not isinstance(attribute.values, list): # force attribute values to list (if attribute is single-valued)
|
||||
attribute.values = [attribute.values]
|
||||
if attr_def.dereference_dn: # try to get object referenced in value
|
||||
if attribute.values:
|
||||
temp_reader = Reader(self.connection, attr_def.dereference_dn, base='', get_operational_attributes=self.get_operational_attributes, controls=self.controls)
|
||||
temp_values = []
|
||||
for element in attribute.values:
|
||||
if entry.entry_dn != element:
|
||||
temp_values.append(temp_reader.search_object(element))
|
||||
else:
|
||||
error_message = 'object %s is referencing itself in the \'%s\' attribute' % (entry.entry_dn, attribute.definition.name)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPObjectDereferenceError(error_message)
|
||||
del temp_reader # remove the temporary Reader
|
||||
attribute.values = temp_values
|
||||
attributes[attribute.key] = attribute
|
||||
if attribute.other_names:
|
||||
attributes.set_alias(attribute.key, attribute.other_names)
|
||||
if attr_def.other_names:
|
||||
attributes.set_alias(attribute.key, attr_def.other_names)
|
||||
used_attribute_names.add(attribute_name)
|
||||
|
||||
if self.attributes:
|
||||
used_attribute_names.update(self.attributes)
|
||||
|
||||
for attribute_name in response['attributes']:
|
||||
if attribute_name not in used_attribute_names:
|
||||
operational_attribute = False
|
||||
# check if the type is an operational attribute
|
||||
if attribute_name in self.schema.attribute_types:
|
||||
if self.schema.attribute_types[attribute_name].no_user_modification or self.schema.attribute_types[attribute_name].usage in [ATTRIBUTE_DIRECTORY_OPERATION, ATTRIBUTE_DISTRIBUTED_OPERATION, ATTRIBUTE_DSA_OPERATION]:
|
||||
operational_attribute = True
|
||||
else:
|
||||
operational_attribute = True
|
||||
if not operational_attribute and attribute_name not in attr_defs and attribute_name.lower() not in conf_attributes_excluded_from_object_def:
|
||||
error_message = 'attribute \'%s\' not in object class \'%s\' for entry %s' % (attribute_name, ', '.join(entry.entry_definition._object_class), entry.entry_dn)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
attribute = OperationalAttribute(AttrDef(conf_operational_attribute_prefix + attribute_name), entry, self)
|
||||
attribute.raw_values = response['raw_attributes'][attribute_name]
|
||||
attribute.values = response['attributes'][attribute_name] if isinstance(response['attributes'][attribute_name], SEQUENCE_TYPES) else [response['attributes'][attribute_name]]
|
||||
if (conf_operational_attribute_prefix + attribute_name) not in attributes:
|
||||
attributes[conf_operational_attribute_prefix + attribute_name] = attribute
|
||||
|
||||
return attributes
|
||||
|
||||
def match_dn(self, dn):
|
||||
"""Return entries with text in DN"""
|
||||
matched = []
|
||||
for entry in self.entries:
|
||||
if dn.lower() in entry.entry_dn.lower():
|
||||
matched.append(entry)
|
||||
return matched
|
||||
|
||||
def match(self, attributes, value):
|
||||
"""Return entries with text in one of the specified attributes"""
|
||||
matched = []
|
||||
if not isinstance(attributes, SEQUENCE_TYPES):
|
||||
attributes = [attributes]
|
||||
|
||||
for entry in self.entries:
|
||||
found = False
|
||||
for attribute in attributes:
|
||||
if attribute in entry:
|
||||
for attr_value in entry[attribute].values:
|
||||
if hasattr(attr_value, 'lower') and hasattr(value, 'lower') and value.lower() in attr_value.lower():
|
||||
found = True
|
||||
elif value == attr_value:
|
||||
found = True
|
||||
if found:
|
||||
matched.append(entry)
|
||||
break
|
||||
if found:
|
||||
break
|
||||
# checks raw values, tries to convert value to byte
|
||||
raw_value = to_raw(value)
|
||||
if isinstance(raw_value, (bytes, bytearray)):
|
||||
for attr_value in entry[attribute].raw_values:
|
||||
if hasattr(attr_value, 'lower') and hasattr(raw_value, 'lower') and raw_value.lower() in attr_value.lower():
|
||||
found = True
|
||||
elif raw_value == attr_value:
|
||||
found = True
|
||||
if found:
|
||||
matched.append(entry)
|
||||
break
|
||||
if found:
|
||||
break
|
||||
return matched
|
||||
|
||||
def _create_entry(self, response):
|
||||
if not response['type'] == 'searchResEntry':
|
||||
return None
|
||||
|
||||
entry = self.entry_class(response['dn'], self) # define an Entry (writable or readonly), as specified in the cursor definition
|
||||
entry._state.attributes = self._get_attributes(response, self.definition._attributes, entry)
|
||||
entry._state.raw_attributes = deepcopy(response['raw_attributes'])
|
||||
|
||||
entry._state.response = response
|
||||
entry._state.read_time = datetime.now()
|
||||
entry._state.set_status(self.entry_initial_status)
|
||||
for attr in entry: # returns the whole attribute object
|
||||
entry.__dict__[attr.key] = attr
|
||||
|
||||
return entry
|
||||
|
||||
def _execute_query(self, query_scope, attributes):
|
||||
if not self.connection:
|
||||
error_message = 'no connection established'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
old_query_filter = None
|
||||
if query_scope == BASE: # requesting a single object so an always-valid filter is set
|
||||
if hasattr(self, 'query_filter'): # only Reader has a query filter
|
||||
old_query_filter = self.query_filter
|
||||
self.query_filter = '(objectclass=*)'
|
||||
else:
|
||||
self._create_query_filter()
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'executing query - base: %s - filter: %s - scope: %s for <%s>', self.base, self.query_filter, query_scope, self)
|
||||
with self.connection:
|
||||
result = self.connection.search(search_base=self.base,
|
||||
search_filter=self.query_filter,
|
||||
search_scope=query_scope,
|
||||
dereference_aliases=self.dereference_aliases,
|
||||
attributes=attributes if attributes else list(self.attributes),
|
||||
get_operational_attributes=self.get_operational_attributes,
|
||||
controls=self.controls)
|
||||
if not self.connection.strategy.sync:
|
||||
response, result, request = self.connection.get_response(result, get_request=True)
|
||||
else:
|
||||
if self.connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
response = self.connection.response
|
||||
result = self.connection.result
|
||||
request = self.connection.request
|
||||
|
||||
self._store_operation_in_history(request, result, response)
|
||||
|
||||
if self._do_not_reset: # trick to not remove entries when using _refresh()
|
||||
return self._create_entry(response[0])
|
||||
|
||||
self.entries = []
|
||||
for r in response:
|
||||
entry = self._create_entry(r)
|
||||
if entry is not None:
|
||||
self.entries.append(entry)
|
||||
if 'objectClass' in entry:
|
||||
for object_class in entry.objectClass:
|
||||
if self.schema and self.schema.object_classes[object_class].kind == CLASS_AUXILIARY and object_class not in self.definition._auxiliary_class:
|
||||
# add auxiliary class to object definition
|
||||
self.definition._auxiliary_class.append(object_class)
|
||||
self.definition._populate_attr_defs(object_class)
|
||||
self.execution_time = datetime.now()
|
||||
|
||||
if old_query_filter: # requesting a single object so an always-valid filter is set
|
||||
self.query_filter = old_query_filter
|
||||
|
||||
def remove(self, entry):
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'removing entry <%s> in <%s>', entry, self)
|
||||
self.entries.remove(entry)
|
||||
|
||||
def _reset_history(self):
|
||||
self._operation_history = list()
|
||||
|
||||
def _store_operation_in_history(self, request, result, response):
|
||||
self._operation_history.append(Operation(request, result, response))
|
||||
|
||||
@property
|
||||
def operations(self):
|
||||
return self._operation_history
|
||||
|
||||
@property
|
||||
def errors(self):
|
||||
return [error for error in self._operation_history if error.result['result'] != RESULT_SUCCESS]
|
||||
|
||||
@property
|
||||
def failed(self):
|
||||
if hasattr(self, '_operation_history'):
|
||||
return any([error.result['result'] != RESULT_SUCCESS for error in self._operation_history])
|
||||
|
||||
|
||||
class Reader(Cursor):
|
||||
"""Reader object to perform searches:
|
||||
|
||||
:param connection: the LDAP connection object to use
|
||||
:type connection: LDAPConnection
|
||||
:param object_def: the ObjectDef of the LDAP object returned
|
||||
:type object_def: ObjectDef
|
||||
:param query: the simplified query (will be transformed in an LDAP filter)
|
||||
:type query: str
|
||||
:param base: starting base of the search
|
||||
:type base: str
|
||||
:param components_in_and: specify if assertions in the query must all be satisfied or not (AND/OR)
|
||||
:type components_in_and: bool
|
||||
:param sub_tree: specify if the search must be performed ad Single Level (False) or Whole SubTree (True)
|
||||
:type sub_tree: bool
|
||||
:param get_operational_attributes: specify if operational attributes are returned or not
|
||||
:type get_operational_attributes: bool
|
||||
:param controls: controls to be used in search
|
||||
:type controls: tuple
|
||||
|
||||
"""
|
||||
entry_class = Entry # entries are read_only
|
||||
attribute_class = Attribute # attributes are read_only
|
||||
entry_initial_status = STATUS_READ
|
||||
|
||||
def __init__(self, connection, object_def, base, query='', components_in_and=True, sub_tree=True, get_operational_attributes=False, attributes=None, controls=None, auxiliary_class=None):
|
||||
Cursor.__init__(self, connection, object_def, get_operational_attributes, attributes, controls, auxiliary_class)
|
||||
self._components_in_and = components_in_and
|
||||
self.sub_tree = sub_tree
|
||||
self._query = query
|
||||
self.base = base
|
||||
self.dereference_aliases = DEREF_ALWAYS
|
||||
self.validated_query = None
|
||||
self._query_dict = dict()
|
||||
self._validated_query_dict = dict()
|
||||
self.query_filter = None
|
||||
self.reset()
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated Reader Cursor: <%r>', self)
|
||||
|
||||
@property
|
||||
def query(self):
|
||||
return self._query
|
||||
|
||||
@query.setter
|
||||
def query(self, value):
|
||||
self._query = value
|
||||
self.reset()
|
||||
|
||||
@property
|
||||
def components_in_and(self):
|
||||
return self._components_in_and
|
||||
|
||||
@components_in_and.setter
|
||||
def components_in_and(self, value):
|
||||
self._components_in_and = value
|
||||
self.reset()
|
||||
|
||||
def clear(self):
|
||||
"""Clear the Reader search parameters
|
||||
|
||||
"""
|
||||
self.dereference_aliases = DEREF_ALWAYS
|
||||
self._reset_history()
|
||||
|
||||
def reset(self):
|
||||
"""Clear all the Reader parameters
|
||||
|
||||
"""
|
||||
self.clear()
|
||||
self.validated_query = None
|
||||
self._query_dict = dict()
|
||||
self._validated_query_dict = dict()
|
||||
self.execution_time = None
|
||||
self.query_filter = None
|
||||
self.entries = []
|
||||
self._create_query_filter()
|
||||
|
||||
def _validate_query(self):
|
||||
"""Processes the text query and verifies that the requested friendly names are in the Reader dictionary
|
||||
If the AttrDef has a 'validate' property the callable is executed and if it returns False an Exception is raised
|
||||
|
||||
"""
|
||||
if not self._query_dict:
|
||||
self._query_dict = _create_query_dict(self._query)
|
||||
|
||||
query = ''
|
||||
for d in sorted(self._query_dict):
|
||||
attr = d[1:] if d[0] in '&|' else d
|
||||
for attr_def in self.definition:
|
||||
if ''.join(attr.split()).lower() == attr_def.key.lower():
|
||||
attr = attr_def.key
|
||||
break
|
||||
if attr in self.definition:
|
||||
vals = sorted(self._query_dict[d].split(';'))
|
||||
|
||||
query += (d[0] + attr if d[0] in '&|' else attr) + ': '
|
||||
for val in vals:
|
||||
val = val.strip()
|
||||
val_not = True if val[0] == '!' else False
|
||||
val_search_operator = '=' # default
|
||||
if val_not:
|
||||
if val[1:].lstrip()[0] not in '=<>~':
|
||||
value = val[1:].lstrip()
|
||||
else:
|
||||
val_search_operator = val[1:].lstrip()[0]
|
||||
value = val[1:].lstrip()[1:]
|
||||
else:
|
||||
if val[0] not in '=<>~':
|
||||
value = val.lstrip()
|
||||
else:
|
||||
val_search_operator = val[0]
|
||||
value = val[1:].lstrip()
|
||||
|
||||
if self.definition[attr].validate:
|
||||
validated = self.definition[attr].validate(value) # returns True, False or a value to substitute to the actual values
|
||||
if validated is False:
|
||||
error_message = 'validation failed for attribute %s and value %s' % (d, val)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
elif validated is not True: # a valid LDAP value equivalent to the actual values
|
||||
value = validated
|
||||
if val_not:
|
||||
query += '!' + val_search_operator + str(value)
|
||||
else:
|
||||
query += val_search_operator + str(value)
|
||||
|
||||
query += ';'
|
||||
query = query[:-1] + ', '
|
||||
else:
|
||||
error_message = 'attribute \'%s\' not in definition' % attr
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
self.validated_query = query[:-2]
|
||||
self._validated_query_dict = _create_query_dict(self.validated_query)
|
||||
|
||||
def _create_query_filter(self):
|
||||
"""Converts the query dictionary to the filter text"""
|
||||
self.query_filter = ''
|
||||
|
||||
if self.definition._object_class:
|
||||
self.query_filter += '(&'
|
||||
if isinstance(self.definition._object_class, SEQUENCE_TYPES) and len(self.definition._object_class) == 1:
|
||||
self.query_filter += '(objectClass=' + self.definition._object_class[0] + ')'
|
||||
elif isinstance(self.definition._object_class, SEQUENCE_TYPES):
|
||||
self.query_filter += '(&'
|
||||
for object_class in self.definition._object_class:
|
||||
self.query_filter += '(objectClass=' + object_class + ')'
|
||||
self.query_filter += ')'
|
||||
else:
|
||||
error_message = 'object class must be a string or a list'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
|
||||
if self._query and self._query.startswith('(') and self._query.endswith(')'): # query is already an LDAP filter
|
||||
if 'objectclass' not in self._query.lower():
|
||||
self.query_filter += self._query + ')' # if objectclass not in filter adds from definition
|
||||
else:
|
||||
self.query_filter = self._query
|
||||
return
|
||||
elif self._query: # if a simplified filter is present
|
||||
if not self.components_in_and:
|
||||
self.query_filter += '(|'
|
||||
elif not self.definition._object_class:
|
||||
self.query_filter += '(&'
|
||||
|
||||
self._validate_query()
|
||||
|
||||
attr_counter = 0
|
||||
for attr in sorted(self._validated_query_dict):
|
||||
attr_counter += 1
|
||||
multi = True if ';' in self._validated_query_dict[attr] else False
|
||||
vals = sorted(self._validated_query_dict[attr].split(';'))
|
||||
attr_def = self.definition[attr[1:]] if attr[0] in '&|' else self.definition[attr]
|
||||
if attr_def.pre_query:
|
||||
modvals = []
|
||||
for val in vals:
|
||||
modvals.append(val[0] + attr_def.pre_query(attr_def.key, val[1:]))
|
||||
vals = modvals
|
||||
if multi:
|
||||
if attr[0] in '&|':
|
||||
self.query_filter += '(' + attr[0]
|
||||
else:
|
||||
self.query_filter += '(|'
|
||||
|
||||
for val in vals:
|
||||
if val[0] == '!':
|
||||
self.query_filter += '(!(' + attr_def.name + _ret_search_value(val[1:]) + '))'
|
||||
else:
|
||||
self.query_filter += '(' + attr_def.name + _ret_search_value(val) + ')'
|
||||
if multi:
|
||||
self.query_filter += ')'
|
||||
|
||||
if not self.components_in_and:
|
||||
self.query_filter += '))'
|
||||
else:
|
||||
self.query_filter += ')'
|
||||
|
||||
if not self.definition._object_class and attr_counter == 1: # removes unneeded starting filter
|
||||
self.query_filter = self.query_filter[2: -1]
|
||||
|
||||
if self.query_filter == '(|)' or self.query_filter == '(&)': # removes empty filter
|
||||
self.query_filter = ''
|
||||
else: # no query, remove unneeded leading (&
|
||||
self.query_filter = self.query_filter[2:]
|
||||
|
||||
def search(self, attributes=None):
|
||||
"""Perform the LDAP search
|
||||
|
||||
:return: Entries found in search
|
||||
|
||||
"""
|
||||
self.clear()
|
||||
query_scope = SUBTREE if self.sub_tree else LEVEL
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'performing search in <%s>', self)
|
||||
self._execute_query(query_scope, attributes)
|
||||
|
||||
return self.entries
|
||||
|
||||
def search_object(self, entry_dn=None, attributes=None): # base must be a single dn
|
||||
"""Perform the LDAP search operation SINGLE_OBJECT scope
|
||||
|
||||
:return: Entry found in search
|
||||
|
||||
"""
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'performing object search in <%s>', self)
|
||||
self.clear()
|
||||
if entry_dn:
|
||||
old_base = self.base
|
||||
self.base = entry_dn
|
||||
self._execute_query(BASE, attributes)
|
||||
self.base = old_base
|
||||
else:
|
||||
self._execute_query(BASE, attributes)
|
||||
|
||||
return self.entries[0] if len(self.entries) > 0 else None
|
||||
|
||||
def search_level(self, attributes=None):
|
||||
"""Perform the LDAP search operation with SINGLE_LEVEL scope
|
||||
|
||||
:return: Entries found in search
|
||||
|
||||
"""
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'performing single level search in <%s>', self)
|
||||
self.clear()
|
||||
self._execute_query(LEVEL, attributes)
|
||||
|
||||
return self.entries
|
||||
|
||||
def search_subtree(self, attributes=None):
|
||||
"""Perform the LDAP search operation WHOLE_SUBTREE scope
|
||||
|
||||
:return: Entries found in search
|
||||
|
||||
"""
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'performing whole subtree search in <%s>', self)
|
||||
self.clear()
|
||||
self._execute_query(SUBTREE, attributes)
|
||||
|
||||
return self.entries
|
||||
|
||||
def _entries_generator(self, responses):
|
||||
for response in responses:
|
||||
yield self._create_entry(response)
|
||||
|
||||
def search_paged(self, paged_size, paged_criticality=True, generator=True, attributes=None):
|
||||
"""Perform a paged search, can be called as an Iterator
|
||||
|
||||
:param attributes: optional attributes to search
|
||||
:param paged_size: number of entries returned in each search
|
||||
:type paged_size: int
|
||||
:param paged_criticality: specify if server must not execute the search if it is not capable of paging searches
|
||||
:type paged_criticality: bool
|
||||
:param generator: if True the paged searches are executed while generating the entries,
|
||||
if False all the paged searches are execute before returning the generator
|
||||
:type generator: bool
|
||||
:return: Entries found in search
|
||||
|
||||
"""
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'performing paged search in <%s> with paged size %s', self, str(paged_size))
|
||||
if not self.connection:
|
||||
error_message = 'no connection established'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
|
||||
self.clear()
|
||||
self._create_query_filter()
|
||||
self.entries = []
|
||||
self.execution_time = datetime.now()
|
||||
response = self.connection.extend.standard.paged_search(search_base=self.base,
|
||||
search_filter=self.query_filter,
|
||||
search_scope=SUBTREE if self.sub_tree else LEVEL,
|
||||
dereference_aliases=self.dereference_aliases,
|
||||
attributes=attributes if attributes else self.attributes,
|
||||
get_operational_attributes=self.get_operational_attributes,
|
||||
controls=self.controls,
|
||||
paged_size=paged_size,
|
||||
paged_criticality=paged_criticality,
|
||||
generator=generator)
|
||||
if generator:
|
||||
return self._entries_generator(response)
|
||||
else:
|
||||
return list(self._entries_generator(response))
|
||||
|
||||
|
||||
class Writer(Cursor):
|
||||
entry_class = WritableEntry
|
||||
attribute_class = WritableAttribute
|
||||
entry_initial_status = STATUS_WRITABLE
|
||||
|
||||
@staticmethod
|
||||
def from_cursor(cursor, connection=None, object_def=None, custom_validator=None):
|
||||
if connection is None:
|
||||
connection = cursor.connection
|
||||
if object_def is None:
|
||||
object_def = cursor.definition
|
||||
writer = Writer(connection, object_def, attributes=cursor.attributes)
|
||||
for entry in cursor.entries:
|
||||
if isinstance(cursor, Reader):
|
||||
entry.entry_writable(object_def, writer, custom_validator=custom_validator)
|
||||
elif isinstance(cursor, Writer):
|
||||
pass
|
||||
else:
|
||||
error_message = 'unknown cursor type %s' % str(type(cursor))
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s', error_message)
|
||||
raise LDAPCursorError(error_message)
|
||||
writer.execution_time = cursor.execution_time
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated Writer Cursor <%r> from cursor <%r>', writer, cursor)
|
||||
return writer
|
||||
|
||||
@staticmethod
|
||||
def from_response(connection, object_def, response=None):
|
||||
if response is None:
|
||||
if not connection.strategy.sync:
|
||||
error_message = 'with asynchronous strategies response must be specified'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s', error_message)
|
||||
raise LDAPCursorError(error_message)
|
||||
elif connection.response:
|
||||
response = connection.response
|
||||
else:
|
||||
error_message = 'response not present'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s', error_message)
|
||||
raise LDAPCursorError(error_message)
|
||||
writer = Writer(connection, object_def)
|
||||
|
||||
for resp in response:
|
||||
if resp['type'] == 'searchResEntry':
|
||||
entry = writer._create_entry(resp)
|
||||
writer.entries.append(entry)
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated Writer Cursor <%r> from response', writer)
|
||||
return writer
|
||||
|
||||
def __init__(self, connection, object_def, get_operational_attributes=False, attributes=None, controls=None, auxiliary_class=None):
|
||||
Cursor.__init__(self, connection, object_def, get_operational_attributes, attributes, controls, auxiliary_class)
|
||||
self.dereference_aliases = DEREF_NEVER
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated Writer Cursor: <%r>', self)
|
||||
|
||||
def commit(self, refresh=True):
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'committed changes for <%s>', self)
|
||||
self._reset_history()
|
||||
successful = True
|
||||
for entry in self.entries:
|
||||
if not entry.entry_commit_changes(refresh=refresh, controls=self.controls, clear_history=False):
|
||||
successful = False
|
||||
|
||||
self.execution_time = datetime.now()
|
||||
|
||||
return successful
|
||||
|
||||
def discard(self):
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'discarded changes for <%s>', self)
|
||||
for entry in self.entries:
|
||||
entry.entry_discard_changes()
|
||||
|
||||
def _refresh_object(self, entry_dn, attributes=None, tries=4, seconds=2, controls=None): # base must be a single dn
|
||||
"""Performs the LDAP search operation SINGLE_OBJECT scope
|
||||
|
||||
:return: Entry found in search
|
||||
|
||||
"""
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'refreshing object <%s> for <%s>', entry_dn, self)
|
||||
if not self.connection:
|
||||
error_message = 'no connection established'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
|
||||
response = []
|
||||
with self.connection:
|
||||
counter = 0
|
||||
while counter < tries:
|
||||
result = self.connection.search(search_base=entry_dn,
|
||||
search_filter='(objectclass=*)',
|
||||
search_scope=BASE,
|
||||
dereference_aliases=DEREF_NEVER,
|
||||
attributes=attributes if attributes else self.attributes,
|
||||
get_operational_attributes=self.get_operational_attributes,
|
||||
controls=controls)
|
||||
if not self.connection.strategy.sync:
|
||||
response, result, request = self.connection.get_response(result, get_request=True)
|
||||
else:
|
||||
if self.connection.strategy.thread_safe:
|
||||
_, result, response, request = result
|
||||
else:
|
||||
response = self.connection.response
|
||||
result = self.connection.result
|
||||
request = self.connection.request
|
||||
|
||||
if result['result'] in [RESULT_SUCCESS]:
|
||||
break
|
||||
sleep(seconds)
|
||||
counter += 1
|
||||
self._store_operation_in_history(request, result, response)
|
||||
|
||||
if len(response) == 1:
|
||||
return self._create_entry(response[0])
|
||||
elif len(response) == 0:
|
||||
return None
|
||||
|
||||
error_message = 'more than 1 entry returned for a single object search'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
|
||||
def new(self, dn):
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'creating new entry <%s> for <%s>', dn, self)
|
||||
dn = safe_dn(dn)
|
||||
for entry in self.entries: # checks if dn is already used in an cursor entry
|
||||
if entry.entry_dn == dn:
|
||||
error_message = 'dn already present in cursor'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
rdns = safe_rdn(dn, decompose=True)
|
||||
entry = self.entry_class(dn, self) # defines a new empty Entry
|
||||
for attr in entry.entry_mandatory_attributes: # defines all mandatory attributes as virtual
|
||||
entry._state.attributes[attr] = self.attribute_class(entry._state.definition[attr], entry, self)
|
||||
entry.__dict__[attr] = entry._state.attributes[attr]
|
||||
entry.objectclass.set(self.definition._object_class)
|
||||
for rdn in rdns: # adds virtual attributes from rdns in entry name (should be more than one with + syntax)
|
||||
if rdn[0] in entry._state.definition._attributes:
|
||||
rdn_name = entry._state.definition._attributes[rdn[0]].name # normalize case folding
|
||||
if rdn_name not in entry._state.attributes:
|
||||
entry._state.attributes[rdn_name] = self.attribute_class(entry._state.definition[rdn_name], entry, self)
|
||||
entry.__dict__[rdn_name] = entry._state.attributes[rdn_name]
|
||||
entry.__dict__[rdn_name].set(rdn[1])
|
||||
else:
|
||||
error_message = 'rdn type \'%s\' not in object class definition' % rdn[0]
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
entry._state.set_status(STATUS_VIRTUAL) # set intial status
|
||||
entry._state.set_status(STATUS_PENDING_CHANGES) # tries to change status to PENDING_CHANGES. If mandatory attributes are missing status is reverted to MANDATORY_MISSING
|
||||
self.entries.append(entry)
|
||||
return entry
|
||||
|
||||
def refresh_entry(self, entry, tries=4, seconds=2):
|
||||
conf_operational_attribute_prefix = get_config_parameter('ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX')
|
||||
|
||||
self._do_not_reset = True
|
||||
attr_list = []
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'refreshing entry <%s> for <%s>', entry, self)
|
||||
for attr in entry._state.attributes: # check friendly attribute name in AttrDef, do not check operational attributes
|
||||
if attr.lower().startswith(conf_operational_attribute_prefix.lower()):
|
||||
continue
|
||||
if entry._state.definition[attr].name:
|
||||
attr_list.append(entry._state.definition[attr].name)
|
||||
else:
|
||||
attr_list.append(entry._state.definition[attr].key)
|
||||
|
||||
temp_entry = self._refresh_object(entry.entry_dn, attr_list, tries, seconds=seconds) # if any attributes is added adds only to the entry not to the definition
|
||||
self._do_not_reset = False
|
||||
if temp_entry:
|
||||
temp_entry._state.origin = entry._state.origin
|
||||
entry.__dict__.clear()
|
||||
entry.__dict__['_state'] = temp_entry._state
|
||||
for attr in entry._state.attributes: # returns the attribute key
|
||||
entry.__dict__[attr] = entry._state.attributes[attr]
|
||||
|
||||
for attr in entry.entry_attributes: # if any attribute of the class was deleted makes it virtual
|
||||
if attr not in entry._state.attributes and attr in entry.entry_definition._attributes:
|
||||
entry._state.attributes[attr] = WritableAttribute(entry.entry_definition[attr], entry, self)
|
||||
entry.__dict__[attr] = entry._state.attributes[attr]
|
||||
entry._state.set_status(entry._state._initial_status)
|
||||
return True
|
||||
return False
|
|
@ -0,0 +1,712 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.08.19
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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/>.
|
||||
|
||||
|
||||
import json
|
||||
try:
|
||||
from collections import OrderedDict
|
||||
except ImportError:
|
||||
from ..utils.ordDict import OrderedDict # for Python 2.6
|
||||
|
||||
from os import linesep
|
||||
from copy import deepcopy
|
||||
|
||||
from .. import STRING_TYPES, SEQUENCE_TYPES, MODIFY_ADD, MODIFY_REPLACE
|
||||
from .attribute import WritableAttribute
|
||||
from .objectDef import ObjectDef
|
||||
from .attrDef import AttrDef
|
||||
from ..core.exceptions import LDAPKeyError, LDAPCursorError, LDAPCursorAttributeError
|
||||
from ..utils.conv import check_json_dict, format_json, prepare_for_stream
|
||||
from ..protocol.rfc2849 import operation_to_ldif, add_ldif_header
|
||||
from ..utils.dn import safe_dn, safe_rdn, to_dn
|
||||
from ..utils.repr import to_stdout_encoding
|
||||
from ..utils.ciDict import CaseInsensitiveWithAliasDict
|
||||
from ..utils.config import get_config_parameter
|
||||
from . import STATUS_VIRTUAL, STATUS_WRITABLE, STATUS_PENDING_CHANGES, STATUS_COMMITTED, STATUS_DELETED,\
|
||||
STATUS_INIT, STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING, STATUS_MANDATORY_MISSING, STATUSES, INITIAL_STATUSES
|
||||
from ..core.results import RESULT_SUCCESS
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED
|
||||
|
||||
|
||||
class EntryState(object):
|
||||
"""Contains data on the status of the entry. Does not pollute the Entry __dict__.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, dn, cursor):
|
||||
self.dn = dn
|
||||
self._initial_status = None
|
||||
self._to = None # used for move and rename
|
||||
self.status = STATUS_INIT
|
||||
self.attributes = CaseInsensitiveWithAliasDict()
|
||||
self.raw_attributes = CaseInsensitiveWithAliasDict()
|
||||
self.response = None
|
||||
self.cursor = cursor
|
||||
self.origin = None # reference to the original read-only entry (set when made writable). Needed to update attributes in read-only when modified (only if both refer the same server)
|
||||
self.read_time = None
|
||||
self.changes = OrderedDict() # includes changes to commit in a writable entry
|
||||
if cursor.definition:
|
||||
self.definition = cursor.definition
|
||||
else:
|
||||
self.definition = None
|
||||
|
||||
def __repr__(self):
|
||||
if self.__dict__ and self.dn is not None:
|
||||
r = 'DN: ' + to_stdout_encoding(self.dn) + ' - STATUS: ' + ((self._initial_status + ', ') if self._initial_status != self.status else '') + self.status + ' - READ TIME: ' + (self.read_time.isoformat() if self.read_time else '<never>') + linesep
|
||||
r += 'attributes: ' + ', '.join(sorted(self.attributes.keys())) + linesep
|
||||
r += 'object def: ' + (', '.join(sorted(self.definition._object_class)) if self.definition._object_class else '<None>') + linesep
|
||||
r += 'attr defs: ' + ', '.join(sorted(self.definition._attributes.keys())) + linesep
|
||||
r += 'response: ' + ('present' if self.response else '<None>') + linesep
|
||||
r += 'cursor: ' + (self.cursor.__class__.__name__ if self.cursor else '<None>') + linesep
|
||||
return r
|
||||
else:
|
||||
return object.__repr__(self)
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
def __getstate__(self):
|
||||
cpy = dict(self.__dict__)
|
||||
cpy['cursor'] = None
|
||||
return cpy
|
||||
|
||||
def set_status(self, status):
|
||||
conf_ignored_mandatory_attributes_in_object_def = [v.lower() for v in get_config_parameter('IGNORED_MANDATORY_ATTRIBUTES_IN_OBJECT_DEF')]
|
||||
if status not in STATUSES:
|
||||
error_message = 'invalid entry status ' + str(status)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
if status in INITIAL_STATUSES:
|
||||
self._initial_status = status
|
||||
self.status = status
|
||||
if status == STATUS_DELETED:
|
||||
self._initial_status = STATUS_VIRTUAL
|
||||
if status == STATUS_COMMITTED:
|
||||
self._initial_status = STATUS_WRITABLE
|
||||
if self.status == STATUS_VIRTUAL or (self.status == STATUS_PENDING_CHANGES and self._initial_status == STATUS_VIRTUAL): # checks if all mandatory attributes are present in new entries
|
||||
for attr in self.definition._attributes:
|
||||
if self.definition._attributes[attr].mandatory and attr.lower() not in conf_ignored_mandatory_attributes_in_object_def:
|
||||
if (attr not in self.attributes or self.attributes[attr].virtual) and attr not in self.changes:
|
||||
self.status = STATUS_MANDATORY_MISSING
|
||||
break
|
||||
|
||||
@property
|
||||
def entry_raw_attributes(self):
|
||||
return self.raw_attributes
|
||||
|
||||
|
||||
class EntryBase(object):
|
||||
"""The Entry object contains a single LDAP entry.
|
||||
Attributes can be accessed either by sequence, by assignment
|
||||
or as dictionary keys. Keys are not case sensitive.
|
||||
|
||||
The Entry object is read only
|
||||
|
||||
- The DN is retrieved by entry_dn
|
||||
- The cursor reference is in _cursor
|
||||
- Raw attributes values are retrieved with _raw_attributes and the _raw_attribute() methods
|
||||
"""
|
||||
|
||||
def __init__(self, dn, cursor):
|
||||
self._state = EntryState(dn, cursor)
|
||||
|
||||
def __repr__(self):
|
||||
if self.__dict__ and self.entry_dn is not None:
|
||||
r = 'DN: ' + to_stdout_encoding(self.entry_dn) + ' - STATUS: ' + ((self._state._initial_status + ', ') if self._state._initial_status != self.entry_status else '') + self.entry_status + ' - READ TIME: ' + (self.entry_read_time.isoformat() if self.entry_read_time else '<never>') + linesep
|
||||
if self._state.attributes:
|
||||
for attr in sorted(self._state.attributes):
|
||||
if self._state.attributes[attr] or (hasattr(self._state.attributes[attr], 'changes') and self._state.attributes[attr].changes):
|
||||
r += ' ' + repr(self._state.attributes[attr]) + linesep
|
||||
return r
|
||||
else:
|
||||
return object.__repr__(self)
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
def __iter__(self):
|
||||
for attribute in self._state.attributes:
|
||||
yield self._state.attributes[attribute]
|
||||
# raise StopIteration # deprecated in PEP 479
|
||||
return
|
||||
|
||||
def __contains__(self, item):
|
||||
try:
|
||||
self.__getitem__(item)
|
||||
return True
|
||||
except LDAPKeyError:
|
||||
return False
|
||||
|
||||
def __getattr__(self, item):
|
||||
if isinstance(item, STRING_TYPES):
|
||||
if item == '_state':
|
||||
return object.__getattr__(self, item)
|
||||
item = ''.join(item.split()).lower()
|
||||
attr_found = None
|
||||
for attr in self._state.attributes.keys():
|
||||
if item == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.aliases():
|
||||
if item == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.keys():
|
||||
if item + ';binary' == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.aliases():
|
||||
if item + ';binary' == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.keys():
|
||||
if item + ';range' in attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.aliases():
|
||||
if item + ';range' in attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
error_message = 'attribute \'%s\' not found' % item
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorAttributeError(error_message)
|
||||
return self._state.attributes[attr]
|
||||
error_message = 'attribute name must be a string'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorAttributeError(error_message)
|
||||
|
||||
def __setattr__(self, item, value):
|
||||
if item == '_state':
|
||||
object.__setattr__(self, item, value)
|
||||
elif item in self._state.attributes:
|
||||
error_message = 'attribute \'%s\' is read only' % item
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorAttributeError(error_message)
|
||||
else:
|
||||
error_message = 'entry is read only, cannot add \'%s\'' % item
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorAttributeError(error_message)
|
||||
|
||||
def __getitem__(self, item):
|
||||
if isinstance(item, STRING_TYPES):
|
||||
item = ''.join(item.split()).lower()
|
||||
attr_found = None
|
||||
for attr in self._state.attributes.keys():
|
||||
if item == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.aliases():
|
||||
if item == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.keys():
|
||||
if item + ';binary' == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
for attr in self._state.attributes.aliases():
|
||||
if item + ';binary' == attr.lower():
|
||||
attr_found = attr
|
||||
break
|
||||
if not attr_found:
|
||||
error_message = 'key \'%s\' not found' % item
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPKeyError(error_message)
|
||||
return self._state.attributes[attr]
|
||||
|
||||
error_message = 'key must be a string'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPKeyError(error_message)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, EntryBase):
|
||||
return self.entry_dn == other.entry_dn
|
||||
|
||||
return False
|
||||
|
||||
def __lt__(self, other):
|
||||
if isinstance(other, EntryBase):
|
||||
return self.entry_dn <= other.entry_dn
|
||||
|
||||
return False
|
||||
|
||||
@property
|
||||
def entry_dn(self):
|
||||
return self._state.dn
|
||||
|
||||
@property
|
||||
def entry_cursor(self):
|
||||
return self._state.cursor
|
||||
|
||||
@property
|
||||
def entry_status(self):
|
||||
return self._state.status
|
||||
|
||||
@property
|
||||
def entry_definition(self):
|
||||
return self._state.definition
|
||||
|
||||
@property
|
||||
def entry_raw_attributes(self):
|
||||
return self._state.raw_attributes
|
||||
|
||||
def entry_raw_attribute(self, name):
|
||||
"""
|
||||
|
||||
:param name: name of the attribute
|
||||
:return: raw (unencoded) value of the attribute, None if attribute is not found
|
||||
"""
|
||||
return self._state.raw_attributes[name] if name in self._state.raw_attributes else None
|
||||
|
||||
@property
|
||||
def entry_mandatory_attributes(self):
|
||||
return [attribute for attribute in self.entry_definition._attributes if self.entry_definition._attributes[attribute].mandatory]
|
||||
|
||||
@property
|
||||
def entry_attributes(self):
|
||||
return list(self._state.attributes.keys())
|
||||
|
||||
@property
|
||||
def entry_attributes_as_dict(self):
|
||||
return dict((attribute_key, deepcopy(attribute_value.values)) for (attribute_key, attribute_value) in self._state.attributes.items())
|
||||
|
||||
@property
|
||||
def entry_read_time(self):
|
||||
return self._state.read_time
|
||||
|
||||
@property
|
||||
def _changes(self):
|
||||
return self._state.changes
|
||||
|
||||
def entry_to_json(self, raw=False, indent=4, sort=True, stream=None, checked_attributes=True, include_empty=True):
|
||||
json_entry = dict()
|
||||
json_entry['dn'] = self.entry_dn
|
||||
if checked_attributes:
|
||||
if not include_empty:
|
||||
# needed for python 2.6 compatibility
|
||||
json_entry['attributes'] = dict((key, self.entry_attributes_as_dict[key]) for key in self.entry_attributes_as_dict if self.entry_attributes_as_dict[key])
|
||||
else:
|
||||
json_entry['attributes'] = self.entry_attributes_as_dict
|
||||
if raw:
|
||||
if not include_empty:
|
||||
# needed for python 2.6 compatibility
|
||||
json_entry['raw'] = dict((key, self.entry_raw_attributes[key]) for key in self.entry_raw_attributes if self.entry_raw_attributes[key])
|
||||
else:
|
||||
json_entry['raw'] = dict(self.entry_raw_attributes)
|
||||
|
||||
if str is bytes: # Python 2
|
||||
check_json_dict(json_entry)
|
||||
|
||||
json_output = json.dumps(json_entry,
|
||||
ensure_ascii=True,
|
||||
sort_keys=sort,
|
||||
indent=indent,
|
||||
check_circular=True,
|
||||
default=format_json,
|
||||
separators=(',', ': '))
|
||||
|
||||
if stream:
|
||||
stream.write(json_output)
|
||||
|
||||
return json_output
|
||||
|
||||
def entry_to_ldif(self, all_base64=False, line_separator=None, sort_order=None, stream=None):
|
||||
ldif_lines = operation_to_ldif('searchResponse', [self._state.response], all_base64, sort_order=sort_order)
|
||||
ldif_lines = add_ldif_header(ldif_lines)
|
||||
line_separator = line_separator or linesep
|
||||
ldif_output = line_separator.join(ldif_lines)
|
||||
if stream:
|
||||
if stream.tell() == 0:
|
||||
header = add_ldif_header(['-'])[0]
|
||||
stream.write(prepare_for_stream(header + line_separator + line_separator))
|
||||
stream.write(prepare_for_stream(ldif_output + line_separator + line_separator))
|
||||
return ldif_output
|
||||
|
||||
|
||||
class Entry(EntryBase):
|
||||
"""The Entry object contains a single LDAP entry.
|
||||
Attributes can be accessed either by sequence, by assignment
|
||||
or as dictionary keys. Keys are not case sensitive.
|
||||
|
||||
The Entry object is read only
|
||||
|
||||
- The DN is retrieved by entry_dn
|
||||
- The Reader reference is in _cursor()
|
||||
- Raw attributes values are retrieved by the _ra_attributes and
|
||||
_raw_attribute() methods
|
||||
|
||||
"""
|
||||
def entry_writable(self, object_def=None, writer_cursor=None, attributes=None, custom_validator=None, auxiliary_class=None):
|
||||
conf_operational_attribute_prefix = get_config_parameter('ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX')
|
||||
if not self.entry_cursor.schema:
|
||||
error_message = 'schema must be available to make an entry writable'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
# returns a new WritableEntry and its Writer cursor
|
||||
if object_def is None:
|
||||
if self.entry_cursor.definition._object_class:
|
||||
object_def = self.entry_definition._object_class
|
||||
auxiliary_class = self.entry_definition._auxiliary_class + (auxiliary_class if isinstance(auxiliary_class, SEQUENCE_TYPES) else [])
|
||||
elif 'objectclass' in self:
|
||||
object_def = self.objectclass.values
|
||||
|
||||
if not object_def:
|
||||
error_message = 'object class must be specified to make an entry writable'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
|
||||
if not isinstance(object_def, ObjectDef):
|
||||
object_def = ObjectDef(object_def, self.entry_cursor.schema, custom_validator, auxiliary_class)
|
||||
|
||||
if attributes:
|
||||
if isinstance(attributes, STRING_TYPES):
|
||||
attributes = [attributes]
|
||||
|
||||
if isinstance(attributes, SEQUENCE_TYPES):
|
||||
for attribute in attributes:
|
||||
if attribute not in object_def._attributes:
|
||||
error_message = 'attribute \'%s\' not in schema for \'%s\'' % (attribute, object_def)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
else:
|
||||
attributes = []
|
||||
|
||||
if not writer_cursor:
|
||||
from .cursor import Writer # local import to avoid circular reference in import at startup
|
||||
writable_cursor = Writer(self.entry_cursor.connection, object_def)
|
||||
else:
|
||||
writable_cursor = writer_cursor
|
||||
|
||||
if attributes: # force reading of attributes
|
||||
writable_entry = writable_cursor._refresh_object(self.entry_dn, list(attributes) + self.entry_attributes)
|
||||
else:
|
||||
writable_entry = writable_cursor._create_entry(self._state.response)
|
||||
writable_cursor.entries.append(writable_entry)
|
||||
writable_entry._state.read_time = self.entry_read_time
|
||||
writable_entry._state.origin = self # reference to the original read-only entry
|
||||
# checks original entry for custom definitions in AttrDefs
|
||||
attr_to_add = []
|
||||
attr_to_remove = []
|
||||
object_def_to_add = []
|
||||
object_def_to_remove = []
|
||||
for attr in writable_entry._state.origin.entry_definition._attributes:
|
||||
original_attr = writable_entry._state.origin.entry_definition._attributes[attr]
|
||||
if attr != original_attr.name and (attr not in writable_entry._state.attributes or conf_operational_attribute_prefix + original_attr.name not in writable_entry._state.attributes):
|
||||
old_attr_def = writable_entry.entry_definition._attributes[original_attr.name]
|
||||
new_attr_def = AttrDef(original_attr.name,
|
||||
key=attr,
|
||||
validate=original_attr.validate,
|
||||
pre_query=original_attr.pre_query,
|
||||
post_query=original_attr.post_query,
|
||||
default=original_attr.default,
|
||||
dereference_dn=original_attr.dereference_dn,
|
||||
description=original_attr.description,
|
||||
mandatory=old_attr_def.mandatory, # keeps value read from schema
|
||||
single_value=old_attr_def.single_value, # keeps value read from schema
|
||||
alias=original_attr.other_names)
|
||||
od = writable_entry.entry_definition
|
||||
object_def_to_remove.append(old_attr_def)
|
||||
object_def_to_add.append(new_attr_def)
|
||||
# updates attribute name in entry attributes
|
||||
new_attr = WritableAttribute(new_attr_def, writable_entry, writable_cursor)
|
||||
if original_attr.name in writable_entry._state.attributes:
|
||||
new_attr.other_names = writable_entry._state.attributes[original_attr.name].other_names
|
||||
new_attr.raw_values = writable_entry._state.attributes[original_attr.name].raw_values
|
||||
new_attr.values = writable_entry._state.attributes[original_attr.name].values
|
||||
new_attr.response = writable_entry._state.attributes[original_attr.name].response
|
||||
attr_to_add.append((attr, new_attr))
|
||||
attr_to_remove.append(original_attr.name)
|
||||
# writable_entry._state.attributes[attr] = new_attr
|
||||
## writable_entry._state.attributes.set_alias(attr, new_attr.other_names)
|
||||
# del writable_entry._state.attributes[original_attr.name]
|
||||
for attr, new_attr in attr_to_add:
|
||||
writable_entry._state.attributes[attr] = new_attr
|
||||
for attr in attr_to_remove:
|
||||
del writable_entry._state.attributes[attr]
|
||||
for object_def in object_def_to_remove:
|
||||
o = writable_entry.entry_definition
|
||||
o -= object_def
|
||||
for object_def in object_def_to_add:
|
||||
o = writable_entry.entry_definition
|
||||
o += object_def
|
||||
|
||||
writable_entry._state.set_status(STATUS_WRITABLE)
|
||||
return writable_entry
|
||||
|
||||
|
||||
class WritableEntry(EntryBase):
|
||||
def __setitem__(self, key, value):
|
||||
if value is not Ellipsis: # hack for using implicit operators in writable attributes
|
||||
self.__setattr__(key, value)
|
||||
|
||||
def __setattr__(self, item, value):
|
||||
conf_attributes_excluded_from_object_def = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_OBJECT_DEF')]
|
||||
if item == '_state' and isinstance(value, EntryState):
|
||||
self.__dict__['_state'] = value
|
||||
return
|
||||
|
||||
if value is not Ellipsis: # hack for using implicit operators in writable attributes
|
||||
# checks if using an alias
|
||||
if item in self.entry_cursor.definition._attributes or item.lower() in conf_attributes_excluded_from_object_def:
|
||||
if item not in self._state.attributes: # setting value to an attribute still without values
|
||||
new_attribute = WritableAttribute(self.entry_cursor.definition._attributes[item], self, cursor=self.entry_cursor)
|
||||
self._state.attributes[str(item)] = new_attribute # force item to a string for key in attributes dict
|
||||
self._state.attributes[item].set(value) # try to add to new_values
|
||||
else:
|
||||
error_message = 'attribute \'%s\' not defined' % item
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorAttributeError(error_message)
|
||||
|
||||
def __getattr__(self, item):
|
||||
if isinstance(item, STRING_TYPES):
|
||||
if item == '_state':
|
||||
return self.__dict__['_state']
|
||||
item = ''.join(item.split()).lower()
|
||||
for attr in self._state.attributes.keys():
|
||||
if item == attr.lower():
|
||||
return self._state.attributes[attr]
|
||||
for attr in self._state.attributes.aliases():
|
||||
if item == attr.lower():
|
||||
return self._state.attributes[attr]
|
||||
if item in self.entry_definition._attributes: # item is a new attribute to commit, creates the AttrDef and add to the attributes to retrive
|
||||
self._state.attributes[item] = WritableAttribute(self.entry_definition._attributes[item], self, self.entry_cursor)
|
||||
self.entry_cursor.attributes.add(item)
|
||||
return self._state.attributes[item]
|
||||
error_message = 'attribute \'%s\' not defined' % item
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorAttributeError(error_message)
|
||||
else:
|
||||
error_message = 'attribute name must be a string'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorAttributeError(error_message)
|
||||
|
||||
@property
|
||||
def entry_virtual_attributes(self):
|
||||
return [attr for attr in self.entry_attributes if self[attr].virtual]
|
||||
|
||||
def entry_commit_changes(self, refresh=True, controls=None, clear_history=True):
|
||||
if clear_history:
|
||||
self.entry_cursor._reset_history()
|
||||
|
||||
if self.entry_status == STATUS_READY_FOR_DELETION:
|
||||
result = self.entry_cursor.connection.delete(self.entry_dn, controls)
|
||||
if not self.entry_cursor.connection.strategy.sync:
|
||||
response, result, request = self.entry_cursor.connection.get_response(result, get_request=True)
|
||||
else:
|
||||
if self.entry_cursor.connection.strategy.thread_safe:
|
||||
_, result, response, request = result
|
||||
else:
|
||||
response = self.entry_cursor.connection.response
|
||||
result = self.entry_cursor.connection.result
|
||||
request = self.entry_cursor.connection.request
|
||||
self.entry_cursor._store_operation_in_history(request, result, response)
|
||||
if result['result'] == RESULT_SUCCESS:
|
||||
dn = self.entry_dn
|
||||
if self._state.origin and self.entry_cursor.connection.server == self._state.origin.entry_cursor.connection.server: # deletes original read-only Entry
|
||||
cursor = self._state.origin.entry_cursor
|
||||
self._state.origin.__dict__.clear()
|
||||
self._state.origin.__dict__['_state'] = EntryState(dn, cursor)
|
||||
self._state.origin._state.set_status(STATUS_DELETED)
|
||||
cursor = self.entry_cursor
|
||||
self.__dict__.clear()
|
||||
self._state = EntryState(dn, cursor)
|
||||
self._state.set_status(STATUS_DELETED)
|
||||
return True
|
||||
return False
|
||||
elif self.entry_status == STATUS_READY_FOR_MOVING:
|
||||
result = self.entry_cursor.connection.modify_dn(self.entry_dn, '+'.join(safe_rdn(self.entry_dn)), new_superior=self._state._to)
|
||||
if not self.entry_cursor.connection.strategy.sync:
|
||||
response, result, request = self.entry_cursor.connection.get_response(result, get_request=True)
|
||||
else:
|
||||
if self.entry_cursor.connection.strategy.thread_safe:
|
||||
_, result, response, request = result
|
||||
else:
|
||||
response = self.entry_cursor.connection.response
|
||||
result = self.entry_cursor.connection.result
|
||||
request = self.entry_cursor.connection.request
|
||||
self.entry_cursor._store_operation_in_history(request, result, response)
|
||||
if result['result'] == RESULT_SUCCESS:
|
||||
self._state.dn = safe_dn('+'.join(safe_rdn(self.entry_dn)) + ',' + self._state._to)
|
||||
if refresh:
|
||||
if self.entry_refresh():
|
||||
if self._state.origin and self.entry_cursor.connection.server == self._state.origin.entry_cursor.connection.server: # refresh dn of origin
|
||||
self._state.origin._state.dn = self.entry_dn
|
||||
self._state.set_status(STATUS_COMMITTED)
|
||||
self._state._to = None
|
||||
return True
|
||||
return False
|
||||
elif self.entry_status == STATUS_READY_FOR_RENAMING:
|
||||
rdn = '+'.join(safe_rdn(self._state._to))
|
||||
result = self.entry_cursor.connection.modify_dn(self.entry_dn, rdn)
|
||||
if not self.entry_cursor.connection.strategy.sync:
|
||||
response, result, request = self.entry_cursor.connection.get_response(result, get_request=True)
|
||||
else:
|
||||
if self.entry_cursor.connection.strategy.thread_safe:
|
||||
_, result, response, request = result
|
||||
else:
|
||||
response = self.entry_cursor.connection.response
|
||||
result = self.entry_cursor.connection.result
|
||||
request = self.entry_cursor.connection.request
|
||||
self.entry_cursor._store_operation_in_history(request, result, response)
|
||||
if result['result'] == RESULT_SUCCESS:
|
||||
self._state.dn = rdn + ',' + ','.join(to_dn(self.entry_dn)[1:])
|
||||
if refresh:
|
||||
if self.entry_refresh():
|
||||
if self._state.origin and self.entry_cursor.connection.server == self._state.origin.entry_cursor.connection.server: # refresh dn of origin
|
||||
self._state.origin._state.dn = self.entry_dn
|
||||
self._state.set_status(STATUS_COMMITTED)
|
||||
self._state._to = None
|
||||
return True
|
||||
return False
|
||||
elif self.entry_status in [STATUS_VIRTUAL, STATUS_MANDATORY_MISSING]:
|
||||
missing_attributes = []
|
||||
for attr in self.entry_mandatory_attributes:
|
||||
if (attr not in self._state.attributes or self._state.attributes[attr].virtual) and attr not in self._changes:
|
||||
missing_attributes.append('\'' + attr + '\'')
|
||||
error_message = 'mandatory attributes %s missing in entry %s' % (', '.join(missing_attributes), self.entry_dn)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
elif self.entry_status == STATUS_PENDING_CHANGES:
|
||||
if self._changes:
|
||||
if self.entry_definition._auxiliary_class: # checks if an attribute is from an auxiliary class and adds it to the objectClass attribute if not present
|
||||
for attr in self._changes:
|
||||
# checks schema to see if attribute is defined in one of the already present object classes
|
||||
attr_classes = self.entry_cursor.schema.attribute_types[attr].mandatory_in + self.entry_cursor.schema.attribute_types[attr].optional_in
|
||||
for object_class in self.objectclass:
|
||||
if object_class in attr_classes:
|
||||
break
|
||||
else: # executed only if the attribute class is not present in the objectClass attribute
|
||||
# checks if attribute is defined in one of the possible auxiliary classes
|
||||
for aux_class in self.entry_definition._auxiliary_class:
|
||||
if aux_class in attr_classes:
|
||||
if self._state._initial_status == STATUS_VIRTUAL: # entry is new, there must be a pending objectClass MODIFY_REPLACE
|
||||
self._changes['objectClass'][0][1].append(aux_class)
|
||||
else:
|
||||
self.objectclass += aux_class
|
||||
if self._state._initial_status == STATUS_VIRTUAL:
|
||||
new_attributes = dict()
|
||||
for attr in self._changes:
|
||||
new_attributes[attr] = self._changes[attr][0][1]
|
||||
result = self.entry_cursor.connection.add(self.entry_dn, None, new_attributes, controls)
|
||||
else:
|
||||
result = self.entry_cursor.connection.modify(self.entry_dn, self._changes, controls)
|
||||
|
||||
if not self.entry_cursor.connection.strategy.sync: # asynchronous request
|
||||
response, result, request = self.entry_cursor.connection.get_response(result, get_request=True)
|
||||
else:
|
||||
if self.entry_cursor.connection.strategy.thread_safe:
|
||||
_, result, response, request = result
|
||||
else:
|
||||
response = self.entry_cursor.connection.response
|
||||
result = self.entry_cursor.connection.result
|
||||
request = self.entry_cursor.connection.request
|
||||
self.entry_cursor._store_operation_in_history(request, result, response)
|
||||
|
||||
if result['result'] == RESULT_SUCCESS:
|
||||
if refresh:
|
||||
if self.entry_refresh():
|
||||
if self._state.origin and self.entry_cursor.connection.server == self._state.origin.entry_cursor.connection.server: # updates original read-only entry if present
|
||||
for attr in self: # adds AttrDefs from writable entry to origin entry definition if some is missing
|
||||
if attr.key in self.entry_definition._attributes and attr.key not in self._state.origin.entry_definition._attributes:
|
||||
self._state.origin.entry_cursor.definition.add_attribute(self.entry_cursor.definition._attributes[attr.key]) # adds AttrDef from writable entry to original entry if missing
|
||||
temp_entry = self._state.origin.entry_cursor._create_entry(self._state.response)
|
||||
self._state.origin.__dict__.clear()
|
||||
self._state.origin.__dict__['_state'] = temp_entry._state
|
||||
for attr in self: # returns the whole attribute object
|
||||
if not hasattr(attr,'virtual'):
|
||||
self._state.origin.__dict__[attr.key] = self._state.origin._state.attributes[attr.key]
|
||||
self._state.origin._state.read_time = self.entry_read_time
|
||||
else:
|
||||
self.entry_discard_changes() # if not refreshed remove committed changes
|
||||
self._state.set_status(STATUS_COMMITTED)
|
||||
return True
|
||||
return False
|
||||
|
||||
def entry_discard_changes(self):
|
||||
self._changes.clear()
|
||||
self._state.set_status(self._state._initial_status)
|
||||
|
||||
def entry_delete(self):
|
||||
if self.entry_status not in [STATUS_WRITABLE, STATUS_COMMITTED, STATUS_READY_FOR_DELETION]:
|
||||
error_message = 'cannot delete entry, invalid status: ' + self.entry_status
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
self._state.set_status(STATUS_READY_FOR_DELETION)
|
||||
|
||||
def entry_refresh(self, tries=4, seconds=2):
|
||||
"""
|
||||
|
||||
Refreshes the entry from the LDAP Server
|
||||
"""
|
||||
if self.entry_cursor.connection:
|
||||
if self.entry_cursor.refresh_entry(self, tries, seconds):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def entry_move(self, destination_dn):
|
||||
if self.entry_status not in [STATUS_WRITABLE, STATUS_COMMITTED, STATUS_READY_FOR_MOVING]:
|
||||
error_message = 'cannot move entry, invalid status: ' + self.entry_status
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
self._state._to = safe_dn(destination_dn)
|
||||
self._state.set_status(STATUS_READY_FOR_MOVING)
|
||||
|
||||
def entry_rename(self, new_name):
|
||||
if self.entry_status not in [STATUS_WRITABLE, STATUS_COMMITTED, STATUS_READY_FOR_RENAMING]:
|
||||
error_message = 'cannot rename entry, invalid status: ' + self.entry_status
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPCursorError(error_message)
|
||||
self._state._to = new_name
|
||||
self._state.set_status(STATUS_READY_FOR_RENAMING)
|
||||
|
||||
@property
|
||||
def entry_changes(self):
|
||||
return self._changes
|
|
@ -0,0 +1,270 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.02.02
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 os import linesep
|
||||
|
||||
from .attrDef import AttrDef
|
||||
from ..core.exceptions import LDAPKeyError, LDAPObjectError, LDAPAttributeError, LDAPSchemaError
|
||||
from .. import STRING_TYPES, SEQUENCE_TYPES, Server, Connection
|
||||
from ..protocol.rfc4512 import SchemaInfo, constant_to_class_kind
|
||||
from ..protocol.formatters.standard import find_attribute_validator
|
||||
from ..utils.ciDict import CaseInsensitiveWithAliasDict
|
||||
from ..utils.config import get_config_parameter
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED
|
||||
|
||||
|
||||
class ObjectDef(object):
|
||||
"""Represent an object in the LDAP server. AttrDefs are stored in a dictionary; the key is the friendly name defined in AttrDef.
|
||||
|
||||
AttrDefs can be added and removed using the += and -= operators
|
||||
|
||||
ObjectDef can be accessed either as a sequence and a dictionary. When accessed the whole AttrDef instance is returned
|
||||
|
||||
"""
|
||||
def __init__(self, object_class=None, schema=None, custom_validator=None, auxiliary_class=None):
|
||||
if object_class is None:
|
||||
object_class = []
|
||||
|
||||
if not isinstance(object_class, SEQUENCE_TYPES):
|
||||
object_class = [object_class]
|
||||
|
||||
if auxiliary_class is None:
|
||||
auxiliary_class = []
|
||||
|
||||
if not isinstance(auxiliary_class, SEQUENCE_TYPES):
|
||||
auxiliary_class = [auxiliary_class]
|
||||
|
||||
self.__dict__['_attributes'] = CaseInsensitiveWithAliasDict()
|
||||
self.__dict__['_custom_validator'] = custom_validator
|
||||
self.__dict__['_oid_info'] = []
|
||||
|
||||
if isinstance(schema, Connection) and (schema._deferred_bind or schema._deferred_open): # probably a lazy connection, tries to bind
|
||||
schema._fire_deferred()
|
||||
|
||||
if schema is not None:
|
||||
if isinstance(schema, Server):
|
||||
schema = schema.schema
|
||||
elif isinstance(schema, Connection):
|
||||
schema = schema.server.schema
|
||||
elif isinstance(schema, SchemaInfo):
|
||||
pass
|
||||
elif schema:
|
||||
error_message = 'unable to read schema'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPSchemaError(error_message)
|
||||
if schema is None:
|
||||
error_message = 'schema not present'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPSchemaError(error_message)
|
||||
self.__dict__['_schema'] = schema
|
||||
|
||||
if self._schema:
|
||||
object_class = [schema.object_classes[name].name[0] for name in object_class] # uses object class names capitalized as in schema
|
||||
auxiliary_class = [schema.object_classes[name].name[0] for name in auxiliary_class]
|
||||
for object_name in object_class:
|
||||
if object_name:
|
||||
self._populate_attr_defs(object_name)
|
||||
|
||||
for object_name in auxiliary_class:
|
||||
if object_name:
|
||||
self._populate_attr_defs(object_name)
|
||||
|
||||
self.__dict__['_object_class'] = object_class
|
||||
self.__dict__['_auxiliary_class'] = auxiliary_class
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated ObjectDef: <%r>', self)
|
||||
|
||||
def _populate_attr_defs(self, object_name):
|
||||
if object_name in self._schema.object_classes:
|
||||
object_schema = self._schema.object_classes[object_name]
|
||||
self.__dict__['_oid_info'].append(object_name + " (" + constant_to_class_kind(object_schema.kind) + ") " + str(object_schema.oid))
|
||||
|
||||
if object_schema.superior:
|
||||
for sup in object_schema.superior:
|
||||
self._populate_attr_defs(sup)
|
||||
for attribute_name in object_schema.must_contain:
|
||||
self.add_from_schema(attribute_name, True)
|
||||
for attribute_name in object_schema.may_contain:
|
||||
if attribute_name not in self._attributes: # the attribute could already be defined as "mandatory" in a superclass
|
||||
self.add_from_schema(attribute_name, False)
|
||||
else:
|
||||
error_message = 'object class \'%s\' not defined in schema' % object_name
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPObjectError(error_message)
|
||||
|
||||
def __repr__(self):
|
||||
if self._object_class:
|
||||
r = 'OBJ : ' + ', '.join(self._object_class) + linesep
|
||||
else:
|
||||
r = 'OBJ : <None>' + linesep
|
||||
if self._auxiliary_class:
|
||||
r += 'AUX : ' + ', '.join(self._auxiliary_class) + linesep
|
||||
else:
|
||||
r += 'AUX : <None>' + linesep
|
||||
r += 'OID: ' + ', '.join([oid for oid in self._oid_info]) + linesep
|
||||
r += 'MUST: ' + ', '.join(sorted([attr for attr in self._attributes if self._attributes[attr].mandatory])) + linesep
|
||||
r += 'MAY : ' + ', '.join(sorted([attr for attr in self._attributes if not self._attributes[attr].mandatory])) + linesep
|
||||
|
||||
return r
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
def __getitem__(self, item):
|
||||
return self.__getattr__(item)
|
||||
|
||||
def __getattr__(self, item):
|
||||
item = ''.join(item.split()).lower()
|
||||
if '_attributes' in self.__dict__:
|
||||
try:
|
||||
return self._attributes[item]
|
||||
except KeyError:
|
||||
error_message = 'key \'%s\' not present' % item
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPKeyError(error_message)
|
||||
else:
|
||||
error_message = 'internal _attributes property not defined'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPKeyError(error_message)
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
error_message = 'object \'%s\' is read only' % key
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPObjectError(error_message)
|
||||
|
||||
def __iadd__(self, other):
|
||||
self.add_attribute(other)
|
||||
return self
|
||||
|
||||
def __isub__(self, other):
|
||||
if isinstance(other, AttrDef):
|
||||
self.remove_attribute(other.key)
|
||||
elif isinstance(other, STRING_TYPES):
|
||||
self.remove_attribute(other)
|
||||
|
||||
return self
|
||||
|
||||
def __iter__(self):
|
||||
for attribute in self._attributes:
|
||||
yield self._attributes[attribute]
|
||||
|
||||
def __len__(self):
|
||||
return len(self._attributes)
|
||||
|
||||
if str is not bytes: # Python 3
|
||||
def __bool__(self): # needed to make the objectDef appears as existing in "if cursor:" even if there are no entries
|
||||
return True
|
||||
else: # Python 2
|
||||
def __nonzero__(self):
|
||||
return True
|
||||
|
||||
def __contains__(self, item):
|
||||
try:
|
||||
self.__getitem__(item)
|
||||
except KeyError:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def add_from_schema(self, attribute_name, mandatory=False):
|
||||
attr_def = AttrDef(attribute_name)
|
||||
attr_def.validate = find_attribute_validator(self._schema, attribute_name, self._custom_validator)
|
||||
attr_def.mandatory = mandatory # in schema mandatory is specified in the object class, not in the attribute class
|
||||
if self._schema and self._schema.attribute_types and attribute_name in self._schema.attribute_types:
|
||||
attr_def.single_value = self._schema.attribute_types[attribute_name].single_value
|
||||
attr_def.oid_info = self._schema.attribute_types[attribute_name]
|
||||
self.add_attribute(attr_def)
|
||||
|
||||
def add_attribute(self, definition=None):
|
||||
"""Add an AttrDef to the ObjectDef. Can be called with the += operator.
|
||||
:param definition: the AttrDef object to add, can also be a string containing the name of attribute to add. Can be a list of both
|
||||
|
||||
"""
|
||||
conf_attributes_excluded_from_object_def = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_OBJECT_DEF')]
|
||||
if isinstance(definition, STRING_TYPES):
|
||||
self.add_from_schema(definition)
|
||||
elif isinstance(definition, AttrDef):
|
||||
if definition.key.lower() not in conf_attributes_excluded_from_object_def:
|
||||
if definition.key not in self._attributes:
|
||||
self._attributes[definition.key] = definition
|
||||
if definition.name and definition.name != definition.key:
|
||||
self._attributes.set_alias(definition.key, definition.name)
|
||||
other_names = [name for name in definition.oid_info.name if definition.key.lower() != name.lower()] if definition.oid_info else None
|
||||
if other_names:
|
||||
self._attributes.set_alias(definition.key, other_names)
|
||||
|
||||
if not definition.validate:
|
||||
validator = find_attribute_validator(self._schema, definition.key, self._custom_validator)
|
||||
self._attributes[definition.key].validate = validator
|
||||
elif isinstance(definition, SEQUENCE_TYPES):
|
||||
for element in definition:
|
||||
self.add_attribute(element)
|
||||
else:
|
||||
error_message = 'unable to add element to object definition'
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPObjectError(error_message)
|
||||
|
||||
def remove_attribute(self, item):
|
||||
"""Remove an AttrDef from the ObjectDef. Can be called with the -= operator.
|
||||
:param item: the AttrDef to remove, can also be a string containing the name of attribute to remove
|
||||
|
||||
"""
|
||||
key = None
|
||||
if isinstance(item, STRING_TYPES):
|
||||
key = ''.join(item.split()).lower()
|
||||
elif isinstance(item, AttrDef):
|
||||
key = item.key.lower()
|
||||
|
||||
if key:
|
||||
for attr in self._attributes:
|
||||
if key == attr.lower():
|
||||
del self._attributes[attr]
|
||||
break
|
||||
else:
|
||||
error_message = 'key \'%s\' not present' % key
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPKeyError(error_message)
|
||||
else:
|
||||
error_message = 'key type must be str or AttrDef not ' + str(type(item))
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', error_message, self)
|
||||
raise LDAPAttributeError(error_message)
|
||||
|
||||
def clear_attributes(self):
|
||||
"""Empty the ObjectDef attribute list
|
||||
|
||||
"""
|
||||
self.__dict__['object_class'] = None
|
||||
self.__dict__['auxiliary_class'] = None
|
||||
self.__dict__['_attributes'] = dict()
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,608 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.05.14
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 os import sep
|
||||
from .results 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 LDAPObjectError(LDAPExceptionError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPAttributeError(LDAPExceptionError, ValueError, TypeError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPCursorError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPCursorAttributeError(LDAPCursorError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPObjectDereferenceError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
# security exceptions
|
||||
class LDAPSSLNotSupportedError(LDAPExceptionError, ImportError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidTlsSpecificationError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidHashAlgorithmError(LDAPExceptionError, ValueError):
|
||||
pass
|
||||
|
||||
class LDAPSignatureVerificationFailedError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
# connection exceptions
|
||||
class LDAPBindError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidServerError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPSASLMechanismNotSupportedError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPConnectionIsReadOnlyError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPChangeError(LDAPExceptionError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPServerPoolError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPServerPoolExhaustedError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidPortError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPStartTLSError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPCertificateError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPUserNameNotAllowedError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPUserNameIsMandatoryError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPPasswordIsMandatoryError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidFilterError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidScopeError(LDAPExceptionError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidDereferenceAliasesError(LDAPExceptionError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInvalidValueError(LDAPExceptionError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPControlError(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
|
||||
|
||||
|
||||
class LDAPTransactionError(LDAPExceptionError):
|
||||
pass
|
||||
|
||||
|
||||
class LDAPInfoError(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):
|
||||
s = []
|
||||
if self.args:
|
||||
if isinstance(self.args, tuple):
|
||||
if len(self.args) > 0:
|
||||
s.append('LDAPMaximumRetriesError: ' + str(self.args[0]))
|
||||
if len(self.args) > 1:
|
||||
s.append('Exception history:')
|
||||
prev_exc = ''
|
||||
for i, exc in enumerate(self.args[1]): # args[1] contains exception history
|
||||
# if str(exc[1]) != prev_exc:
|
||||
# s.append((str(i).rjust(5) + ' ' + str(exc[0]) + ': ' + str(exc[1]) + ' - ' + str(exc[2])))
|
||||
# prev_exc = str(exc[1])
|
||||
if str(exc) != prev_exc:
|
||||
s.append((str(i).rjust(5) + ' ' + str(type(exc)) + ': ' + str(exc)))
|
||||
prev_exc = str(exc)
|
||||
if len(self.args) > 2:
|
||||
s.append('Maximum number of retries reached: ' + str(self.args[2]))
|
||||
else:
|
||||
s = [LDAPExceptionError.__str__(self)]
|
||||
|
||||
return sep.join(s)
|
||||
|
||||
|
||||
# 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):
|
||||
"""
|
||||
Generates a new exception class of the requested type merged with the exception raised by the interpreter
|
||||
"""
|
||||
return type(LDAPStartTLSError.__name__, (LDAPStartTLSError, type(exc)), dict())
|
|
@ -0,0 +1,329 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.03.14
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 datetime import datetime, MINYEAR
|
||||
from os import linesep
|
||||
from random import randint
|
||||
from time import sleep
|
||||
|
||||
from .. import FIRST, ROUND_ROBIN, RANDOM, SEQUENCE_TYPES, STRING_TYPES, get_config_parameter
|
||||
from .exceptions import LDAPUnknownStrategyError, LDAPServerPoolError, LDAPServerPoolExhaustedError
|
||||
from .server import Server
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, NETWORK
|
||||
|
||||
POOLING_STRATEGIES = [FIRST, ROUND_ROBIN, RANDOM]
|
||||
|
||||
|
||||
class ServerState(object):
|
||||
def __init__(self, server, last_checked_time, available):
|
||||
self.server = server
|
||||
self.last_checked_time = last_checked_time
|
||||
self.available = available
|
||||
|
||||
|
||||
class ServerPoolState(object):
|
||||
def __init__(self, server_pool):
|
||||
self.server_states = [] # each element is a ServerState
|
||||
self.strategy = server_pool.strategy
|
||||
self.server_pool = server_pool
|
||||
self.last_used_server = 0
|
||||
self.refresh()
|
||||
self.initialize_time = datetime.now()
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated ServerPoolState: <%r>', self)
|
||||
|
||||
def __str__(self):
|
||||
s = 'servers: ' + linesep
|
||||
if self.server_states:
|
||||
for state in self.server_states:
|
||||
s += str(state.server) + linesep
|
||||
else:
|
||||
s += 'None' + linesep
|
||||
s += 'Pool strategy: ' + str(self.strategy) + linesep
|
||||
s += ' - Last used server: ' + ('None' if self.last_used_server == -1 else str(self.server_states[self.last_used_server].server))
|
||||
|
||||
return s
|
||||
|
||||
def refresh(self):
|
||||
self.server_states = []
|
||||
for server in self.server_pool.servers:
|
||||
self.server_states.append(ServerState(server, datetime(MINYEAR, 1, 1), True)) # server, smallest date ever, supposed available
|
||||
self.last_used_server = randint(0, len(self.server_states) - 1)
|
||||
|
||||
def get_current_server(self):
|
||||
return self.server_states[self.last_used_server].server
|
||||
|
||||
def get_server(self):
|
||||
if self.server_states:
|
||||
if self.server_pool.strategy == FIRST:
|
||||
if self.server_pool.active:
|
||||
# returns the first active server
|
||||
self.last_used_server = self.find_active_server(starting=0)
|
||||
else:
|
||||
# returns always the first server - no pooling
|
||||
self.last_used_server = 0
|
||||
elif self.server_pool.strategy == ROUND_ROBIN:
|
||||
if self.server_pool.active:
|
||||
# returns the next active server in a circular range
|
||||
self.last_used_server = self.find_active_server(self.last_used_server + 1)
|
||||
else:
|
||||
# returns the next server in a circular range
|
||||
self.last_used_server = self.last_used_server + 1 if (self.last_used_server + 1) < len(self.server_states) else 0
|
||||
elif self.server_pool.strategy == RANDOM:
|
||||
if self.server_pool.active:
|
||||
self.last_used_server = self.find_active_random_server()
|
||||
else:
|
||||
# returns a random server in the pool
|
||||
self.last_used_server = randint(0, len(self.server_states) - 1)
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'unknown server pooling strategy <%s>', self.server_pool.strategy)
|
||||
raise LDAPUnknownStrategyError('unknown server pooling strategy')
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'server returned from Server Pool: <%s>', self.last_used_server)
|
||||
return self.server_states[self.last_used_server].server
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'no servers in Server Pool <%s>', self)
|
||||
raise LDAPServerPoolError('no servers in server pool')
|
||||
|
||||
def find_active_random_server(self):
|
||||
counter = self.server_pool.active # can be True for "forever" or the number of cycles to try
|
||||
while counter:
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'entering loop for finding active server in pool <%s>', self)
|
||||
temp_list = self.server_states[:] # copy
|
||||
while temp_list:
|
||||
# pops a random server from a temp list and checks its
|
||||
# availability, if not available tries another one
|
||||
server_state = temp_list.pop(randint(0, len(temp_list) - 1))
|
||||
if not server_state.available: # server is offline
|
||||
if (isinstance(self.server_pool.exhaust, bool) and self.server_pool.exhaust) or (datetime.now() - server_state.last_checked_time).seconds < self.server_pool.exhaust: # keeps server offline
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'server <%s> excluded from checking because it is offline', server_state.server)
|
||||
continue
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'server <%s> reinserted in pool', server_state.server)
|
||||
server_state.last_checked_time = datetime.now()
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'checking server <%s> for availability', server_state.server)
|
||||
if server_state.server.check_availability():
|
||||
# returns a random active server in the pool
|
||||
server_state.available = True
|
||||
return self.server_states.index(server_state)
|
||||
else:
|
||||
server_state.available = False
|
||||
if not isinstance(self.server_pool.active, bool):
|
||||
counter -= 1
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'no random active server available in Server Pool <%s> after maximum number of tries', self)
|
||||
raise LDAPServerPoolExhaustedError('no random active server available in server pool after maximum number of tries')
|
||||
|
||||
def find_active_server(self, starting):
|
||||
conf_pool_timeout = get_config_parameter('POOLING_LOOP_TIMEOUT')
|
||||
counter = self.server_pool.active # can be True for "forever" or the number of cycles to try
|
||||
if starting >= len(self.server_states):
|
||||
starting = 0
|
||||
|
||||
while counter:
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'entering loop number <%s> for finding active server in pool <%s>', counter, self)
|
||||
index = -1
|
||||
pool_size = len(self.server_states)
|
||||
while index < pool_size - 1:
|
||||
index += 1
|
||||
offset = index + starting if index + starting < pool_size else index + starting - pool_size
|
||||
server_state = self.server_states[offset]
|
||||
if not server_state.available: # server is offline
|
||||
if (isinstance(self.server_pool.exhaust, bool) and self.server_pool.exhaust) or (datetime.now() - server_state.last_checked_time).seconds < self.server_pool.exhaust: # keeps server offline
|
||||
if log_enabled(NETWORK):
|
||||
if isinstance(self.server_pool.exhaust, bool):
|
||||
log(NETWORK, 'server <%s> excluded from checking because is offline', server_state.server)
|
||||
else:
|
||||
log(NETWORK, 'server <%s> excluded from checking because is offline for %d seconds', server_state.server, (self.server_pool.exhaust - (datetime.now() - server_state.last_checked_time).seconds))
|
||||
continue
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'server <%s> reinserted in pool', server_state.server)
|
||||
server_state.last_checked_time = datetime.now()
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'checking server <%s> for availability', server_state.server)
|
||||
if server_state.server.check_availability():
|
||||
server_state.available = True
|
||||
return offset
|
||||
else:
|
||||
server_state.available = False # sets server offline
|
||||
|
||||
if not isinstance(self.server_pool.active, bool):
|
||||
counter -= 1
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'waiting for %d seconds before retrying pool servers cycle', conf_pool_timeout)
|
||||
sleep(conf_pool_timeout)
|
||||
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'no active server available in Server Pool <%s> after maximum number of tries', self)
|
||||
raise LDAPServerPoolExhaustedError('no active server available in server pool after maximum number of tries')
|
||||
|
||||
def __len__(self):
|
||||
return len(self.server_states)
|
||||
|
||||
|
||||
class ServerPool(object):
|
||||
def __init__(self,
|
||||
servers=None,
|
||||
pool_strategy=ROUND_ROBIN,
|
||||
active=True,
|
||||
exhaust=False,
|
||||
single_state=True):
|
||||
|
||||
if pool_strategy not in POOLING_STRATEGIES:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'unknown pooling strategy <%s>', pool_strategy)
|
||||
raise LDAPUnknownStrategyError('unknown pooling strategy')
|
||||
if exhaust and not active:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'cannot instantiate pool with exhaust and not active')
|
||||
raise LDAPServerPoolError('pools can be exhausted only when checking for active servers')
|
||||
self.servers = []
|
||||
self.pool_states = dict()
|
||||
self.active = active
|
||||
self.exhaust = exhaust
|
||||
self.single = single_state
|
||||
self._pool_state = None # used for storing the global state of the pool
|
||||
if isinstance(servers, SEQUENCE_TYPES + (Server, )):
|
||||
self.add(servers)
|
||||
elif isinstance(servers, STRING_TYPES):
|
||||
self.add(Server(servers))
|
||||
self.strategy = pool_strategy
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated ServerPool: <%r>', self)
|
||||
|
||||
def __str__(self):
|
||||
s = 'servers: ' + linesep
|
||||
if self.servers:
|
||||
for server in self.servers:
|
||||
s += str(server) + linesep
|
||||
else:
|
||||
s += 'None' + linesep
|
||||
s += 'Pool strategy: ' + str(self.strategy)
|
||||
s += ' - ' + 'active: ' + (str(self.active) if self.active else 'False')
|
||||
s += ' - ' + 'exhaust pool: ' + (str(self.exhaust) if self.exhaust else 'False')
|
||||
return s
|
||||
|
||||
def __repr__(self):
|
||||
r = 'ServerPool(servers='
|
||||
if self.servers:
|
||||
r += '['
|
||||
for server in self.servers:
|
||||
r += server.__repr__() + ', '
|
||||
r = r[:-2] + ']'
|
||||
else:
|
||||
r += 'None'
|
||||
r += ', pool_strategy={0.strategy!r}'.format(self)
|
||||
r += ', active={0.active!r}'.format(self)
|
||||
r += ', exhaust={0.exhaust!r}'.format(self)
|
||||
r += ')'
|
||||
|
||||
return r
|
||||
|
||||
def __len__(self):
|
||||
return len(self.servers)
|
||||
|
||||
def __getitem__(self, item):
|
||||
return self.servers[item]
|
||||
|
||||
def __iter__(self):
|
||||
return self.servers.__iter__()
|
||||
|
||||
def add(self, servers):
|
||||
if isinstance(servers, Server):
|
||||
if servers not in self.servers:
|
||||
self.servers.append(servers)
|
||||
elif isinstance(servers, STRING_TYPES):
|
||||
self.servers.append(Server(servers))
|
||||
elif isinstance(servers, SEQUENCE_TYPES):
|
||||
for server in servers:
|
||||
if isinstance(server, Server):
|
||||
self.servers.append(server)
|
||||
elif isinstance(server, STRING_TYPES):
|
||||
self.servers.append(Server(server))
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'element must be a server in Server Pool <%s>', self)
|
||||
raise LDAPServerPoolError('server in ServerPool must be a Server')
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'server must be a Server of a list of Servers when adding to Server Pool <%s>', self)
|
||||
raise LDAPServerPoolError('server must be a Server or a list of Server')
|
||||
|
||||
if self.single:
|
||||
if self._pool_state:
|
||||
self._pool_state.refresh()
|
||||
else:
|
||||
for connection in self.pool_states:
|
||||
# notifies connections using this pool to refresh
|
||||
self.pool_states[connection].refresh()
|
||||
|
||||
def remove(self, server):
|
||||
if server in self.servers:
|
||||
self.servers.remove(server)
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'server %s to be removed not in Server Pool <%s>', server, self)
|
||||
raise LDAPServerPoolError('server not in server pool')
|
||||
|
||||
if self.single:
|
||||
if self._pool_state:
|
||||
self._pool_state.refresh()
|
||||
else:
|
||||
for connection in self.pool_states:
|
||||
# notifies connections using this pool to refresh
|
||||
self.pool_states[connection].refresh()
|
||||
|
||||
def initialize(self, connection):
|
||||
# registers pool_state in ServerPool object
|
||||
if self.single:
|
||||
if not self._pool_state:
|
||||
self._pool_state = ServerPoolState(self)
|
||||
self.pool_states[connection] = self._pool_state
|
||||
else:
|
||||
self.pool_states[connection] = ServerPoolState(self)
|
||||
|
||||
def get_server(self, connection):
|
||||
if connection in self.pool_states:
|
||||
return self.pool_states[connection].get_server()
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'connection <%s> not in Server Pool State <%s>', connection, self)
|
||||
raise LDAPServerPoolError('connection not in ServerPoolState')
|
||||
|
||||
def get_current_server(self, connection):
|
||||
if connection in self.pool_states:
|
||||
return self.pool_states[connection].get_current_server()
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'connection <%s> not in Server Pool State <%s>', connection, self)
|
||||
raise LDAPServerPoolError('connection not in ServerPoolState')
|
|
@ -0,0 +1,68 @@
|
|||
""" Utilities and constants related to reverse dns lookup """
|
||||
|
||||
# Created on 2020.09.16
|
||||
#
|
||||
# Author: Azaria Zornberg
|
||||
#
|
||||
# Copyright 2020 Giovanni Cannata
|
||||
# Copyright 2020 Azaria Zornberg
|
||||
#
|
||||
# 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/>.
|
||||
|
||||
import socket
|
||||
|
||||
|
||||
class ReverseDnsSetting(object):
|
||||
OFF = 0,
|
||||
REQUIRE_RESOLVE_ALL_ADDRESSES = 1,
|
||||
REQUIRE_RESOLVE_IP_ADDRESSES_ONLY = 2,
|
||||
OPTIONAL_RESOLVE_ALL_ADDRESSES = 3,
|
||||
OPTIONAL_RESOLVE_IP_ADDRESSES_ONLY = 4,
|
||||
SUPPORTED_VALUES = {OFF, REQUIRE_RESOLVE_ALL_ADDRESSES, REQUIRE_RESOLVE_IP_ADDRESSES_ONLY,
|
||||
OPTIONAL_RESOLVE_ALL_ADDRESSES, OPTIONAL_RESOLVE_IP_ADDRESSES_ONLY}
|
||||
|
||||
|
||||
def get_hostname_by_addr(addr, success_required=True):
|
||||
""" Resolve the hostname for an ip address. If success is required, raise an exception if a hostname cannot
|
||||
be resolved for the address.
|
||||
Returns the hostname resolved for the address.
|
||||
If success is not required, returns None for addresses that do not resolve to hostnames.
|
||||
"""
|
||||
try:
|
||||
return socket.gethostbyaddr(addr)[0]
|
||||
except Exception as ex:
|
||||
# if we need to succeed, just re-raise
|
||||
if success_required:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def is_ip_addr(addr):
|
||||
"""Returns True if an address is an ipv4 address or an ipv6 address based on format. False otherwise."""
|
||||
for addr_type in [socket.AF_INET, socket.AF_INET6]:
|
||||
try:
|
||||
socket.inet_pton(addr_type, addr) # not present on python 2.7 on Windows
|
||||
return True
|
||||
except AttributeError: # not present on Windows, always valid
|
||||
if '.' in addr and any([c.isalpha() for c in addr.replace('.', '')]): # not an IPv4 address, probably an hostname
|
||||
return False
|
||||
else: # do not check for ipv6
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return False
|
|
@ -0,0 +1,137 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.08.31
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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/>.
|
||||
|
||||
|
||||
# result codes
|
||||
RESULT_SUCCESS = 0
|
||||
RESULT_OPERATIONS_ERROR = 1
|
||||
RESULT_PROTOCOL_ERROR = 2
|
||||
RESULT_TIME_LIMIT_EXCEEDED = 3
|
||||
RESULT_SIZE_LIMIT_EXCEEDED = 4
|
||||
RESULT_COMPARE_FALSE = 5
|
||||
RESULT_COMPARE_TRUE = 6
|
||||
RESULT_AUTH_METHOD_NOT_SUPPORTED = 7
|
||||
RESULT_STRONGER_AUTH_REQUIRED = 8
|
||||
RESULT_RESERVED = 9
|
||||
RESULT_REFERRAL = 10
|
||||
RESULT_ADMIN_LIMIT_EXCEEDED = 11
|
||||
RESULT_UNAVAILABLE_CRITICAL_EXTENSION = 12
|
||||
RESULT_CONFIDENTIALITY_REQUIRED = 13
|
||||
RESULT_SASL_BIND_IN_PROGRESS = 14
|
||||
RESULT_NO_SUCH_ATTRIBUTE = 16
|
||||
RESULT_UNDEFINED_ATTRIBUTE_TYPE = 17
|
||||
RESULT_INAPPROPRIATE_MATCHING = 18
|
||||
RESULT_CONSTRAINT_VIOLATION = 19
|
||||
RESULT_ATTRIBUTE_OR_VALUE_EXISTS = 20
|
||||
RESULT_INVALID_ATTRIBUTE_SYNTAX = 21
|
||||
RESULT_NO_SUCH_OBJECT = 32
|
||||
RESULT_ALIAS_PROBLEM = 33
|
||||
RESULT_INVALID_DN_SYNTAX = 34
|
||||
RESULT_ALIAS_DEREFERENCING_PROBLEM = 36
|
||||
RESULT_INAPPROPRIATE_AUTHENTICATION = 48
|
||||
RESULT_INVALID_CREDENTIALS = 49
|
||||
RESULT_INSUFFICIENT_ACCESS_RIGHTS = 50
|
||||
RESULT_BUSY = 51
|
||||
RESULT_UNAVAILABLE = 52
|
||||
RESULT_UNWILLING_TO_PERFORM = 53
|
||||
RESULT_LOOP_DETECTED = 54
|
||||
RESULT_NAMING_VIOLATION = 64
|
||||
RESULT_OBJECT_CLASS_VIOLATION = 65
|
||||
RESULT_NOT_ALLOWED_ON_NON_LEAF = 66
|
||||
RESULT_NOT_ALLOWED_ON_RDN = 67
|
||||
RESULT_ENTRY_ALREADY_EXISTS = 68
|
||||
RESULT_OBJECT_CLASS_MODS_PROHIBITED = 69
|
||||
RESULT_AFFECT_MULTIPLE_DSAS = 71
|
||||
RESULT_OTHER = 80
|
||||
RESULT_LCUP_RESOURCES_EXHAUSTED = 113
|
||||
RESULT_LCUP_SECURITY_VIOLATION = 114
|
||||
RESULT_LCUP_INVALID_DATA = 115
|
||||
RESULT_LCUP_UNSUPPORTED_SCHEME = 116
|
||||
RESULT_LCUP_RELOAD_REQUIRED = 117
|
||||
RESULT_CANCELED = 118
|
||||
RESULT_NO_SUCH_OPERATION = 119
|
||||
RESULT_TOO_LATE = 120
|
||||
RESULT_CANNOT_CANCEL = 121
|
||||
RESULT_ASSERTION_FAILED = 122
|
||||
RESULT_AUTHORIZATION_DENIED = 123
|
||||
RESULT_E_SYNC_REFRESH_REQUIRED = 4096
|
||||
|
||||
RESULT_CODES = {
|
||||
RESULT_SUCCESS: 'success',
|
||||
RESULT_OPERATIONS_ERROR: 'operationsError',
|
||||
RESULT_PROTOCOL_ERROR: 'protocolError',
|
||||
RESULT_TIME_LIMIT_EXCEEDED: 'timeLimitExceeded',
|
||||
RESULT_SIZE_LIMIT_EXCEEDED: 'sizeLimitExceeded',
|
||||
RESULT_COMPARE_FALSE: 'compareFalse',
|
||||
RESULT_COMPARE_TRUE: 'compareTrue',
|
||||
RESULT_AUTH_METHOD_NOT_SUPPORTED: 'authMethodNotSupported',
|
||||
RESULT_RESERVED: 'reserved',
|
||||
RESULT_STRONGER_AUTH_REQUIRED: 'strongerAuthRequired',
|
||||
RESULT_REFERRAL: 'referral',
|
||||
RESULT_ADMIN_LIMIT_EXCEEDED: 'adminLimitExceeded',
|
||||
RESULT_UNAVAILABLE_CRITICAL_EXTENSION: 'unavailableCriticalExtension',
|
||||
RESULT_CONFIDENTIALITY_REQUIRED: 'confidentialityRequired',
|
||||
RESULT_SASL_BIND_IN_PROGRESS: 'saslBindInProgress',
|
||||
RESULT_NO_SUCH_ATTRIBUTE: 'noSuchAttribute',
|
||||
RESULT_UNDEFINED_ATTRIBUTE_TYPE: 'undefinedAttributeType',
|
||||
RESULT_INAPPROPRIATE_MATCHING: 'inappropriateMatching',
|
||||
RESULT_CONSTRAINT_VIOLATION: 'constraintViolation',
|
||||
RESULT_ATTRIBUTE_OR_VALUE_EXISTS: 'attributeOrValueExists',
|
||||
RESULT_INVALID_ATTRIBUTE_SYNTAX: 'invalidAttributeSyntax',
|
||||
RESULT_NO_SUCH_OBJECT: 'noSuchObject',
|
||||
RESULT_ALIAS_PROBLEM: 'aliasProblem',
|
||||
RESULT_INVALID_DN_SYNTAX: 'invalidDNSyntax',
|
||||
RESULT_ALIAS_DEREFERENCING_PROBLEM: 'aliasDereferencingProblem',
|
||||
RESULT_INAPPROPRIATE_AUTHENTICATION: 'inappropriateAuthentication',
|
||||
RESULT_INVALID_CREDENTIALS: 'invalidCredentials',
|
||||
RESULT_INSUFFICIENT_ACCESS_RIGHTS: 'insufficientAccessRights',
|
||||
RESULT_BUSY: 'busy',
|
||||
RESULT_UNAVAILABLE: 'unavailable',
|
||||
RESULT_UNWILLING_TO_PERFORM: 'unwillingToPerform',
|
||||
RESULT_LOOP_DETECTED: 'loopDetected',
|
||||
RESULT_NAMING_VIOLATION: 'namingViolation',
|
||||
RESULT_OBJECT_CLASS_VIOLATION: 'objectClassViolation',
|
||||
RESULT_NOT_ALLOWED_ON_NON_LEAF: 'notAllowedOnNonLeaf',
|
||||
RESULT_NOT_ALLOWED_ON_RDN: 'notAllowedOnRDN',
|
||||
RESULT_ENTRY_ALREADY_EXISTS: 'entryAlreadyExists',
|
||||
RESULT_OBJECT_CLASS_MODS_PROHIBITED: 'objectClassModsProhibited',
|
||||
RESULT_AFFECT_MULTIPLE_DSAS: 'affectMultipleDSAs',
|
||||
RESULT_OTHER: 'other',
|
||||
RESULT_LCUP_RESOURCES_EXHAUSTED: 'lcupResourcesExhausted',
|
||||
RESULT_LCUP_SECURITY_VIOLATION: 'lcupSecurityViolation',
|
||||
RESULT_LCUP_INVALID_DATA: 'lcupInvalidData',
|
||||
RESULT_LCUP_UNSUPPORTED_SCHEME: 'lcupUnsupportedScheme',
|
||||
RESULT_LCUP_RELOAD_REQUIRED: 'lcupReloadRequired',
|
||||
RESULT_CANCELED: 'canceled',
|
||||
RESULT_NO_SUCH_OPERATION: 'noSuchOperation',
|
||||
RESULT_TOO_LATE: 'tooLate',
|
||||
RESULT_CANNOT_CANCEL: 'cannotCancel',
|
||||
RESULT_ASSERTION_FAILED: 'assertionFailed',
|
||||
RESULT_AUTHORIZATION_DENIED: 'authorizationDenied',
|
||||
RESULT_E_SYNC_REFRESH_REQUIRED: 'e-syncRefreshRequired'
|
||||
}
|
||||
|
||||
# do not raise exception for (in raise_exceptions connection mode)
|
||||
DO_NOT_RAISE_EXCEPTIONS = [RESULT_SUCCESS, RESULT_COMPARE_FALSE, RESULT_COMPARE_TRUE, RESULT_REFERRAL, RESULT_SASL_BIND_IN_PROGRESS, RESULT_SIZE_LIMIT_EXCEEDED, RESULT_TIME_LIMIT_EXCEEDED]
|
|
@ -0,0 +1,682 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.05.31
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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/>.
|
||||
|
||||
import socket
|
||||
from threading import Lock
|
||||
from datetime import datetime, MINYEAR
|
||||
|
||||
from .. import DSA, SCHEMA, ALL, BASE, get_config_parameter, OFFLINE_EDIR_8_8_8, OFFLINE_EDIR_9_1_4, OFFLINE_AD_2012_R2, OFFLINE_SLAPD_2_4, OFFLINE_DS389_1_3_3, SEQUENCE_TYPES, IP_SYSTEM_DEFAULT, IP_V4_ONLY, IP_V6_ONLY, IP_V4_PREFERRED, IP_V6_PREFERRED, STRING_TYPES
|
||||
from .exceptions import LDAPInvalidServerError, LDAPDefinitionError, LDAPInvalidPortError, LDAPInvalidTlsSpecificationError, LDAPSocketOpenError, LDAPInfoError
|
||||
from ..protocol.formatters.standard import format_attribute_values
|
||||
from ..protocol.rfc4511 import LDAP_MAX_INT
|
||||
from ..protocol.rfc4512 import SchemaInfo, DsaInfo
|
||||
from .tls import Tls
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, NETWORK
|
||||
from ..utils.conv import to_unicode
|
||||
from ..utils.port_validators import check_port, check_port_and_port_list
|
||||
|
||||
try:
|
||||
from urllib.parse import unquote # Python 3
|
||||
except ImportError:
|
||||
from urllib import unquote # Python 2
|
||||
|
||||
try: # try to discover if unix sockets are available for LDAP over IPC (ldapi:// scheme)
|
||||
# noinspection PyUnresolvedReferences
|
||||
from socket import AF_UNIX
|
||||
unix_socket_available = True
|
||||
except ImportError:
|
||||
unix_socket_available = False
|
||||
|
||||
|
||||
class Server(object):
|
||||
"""
|
||||
LDAP Server definition class
|
||||
|
||||
Allowed_referral_hosts can be None (default), or a list of tuples of
|
||||
allowed servers ip address or names to contact while redirecting
|
||||
search to referrals.
|
||||
|
||||
The second element of the tuple is a boolean to indicate if
|
||||
authentication to that server is allowed; if False only anonymous
|
||||
bind will be used.
|
||||
|
||||
Per RFC 4516. Use [('*', False)] to allow any host with anonymous
|
||||
bind, use [('*', True)] to allow any host with same authentication of
|
||||
Server.
|
||||
"""
|
||||
|
||||
_message_counter = 0
|
||||
_message_id_lock = Lock() # global lock for message_id shared by all Server objects
|
||||
|
||||
def __init__(self,
|
||||
host,
|
||||
port=None,
|
||||
use_ssl=False,
|
||||
allowed_referral_hosts=None,
|
||||
get_info=SCHEMA,
|
||||
tls=None,
|
||||
formatter=None,
|
||||
connect_timeout=None,
|
||||
mode=IP_V6_PREFERRED,
|
||||
validator=None):
|
||||
|
||||
self.ipc = False
|
||||
url_given = False
|
||||
host = host.strip()
|
||||
if host.lower().startswith('ldap://'):
|
||||
self.host = host[7:]
|
||||
use_ssl = False
|
||||
url_given = True
|
||||
elif host.lower().startswith('ldaps://'):
|
||||
self.host = host[8:]
|
||||
use_ssl = True
|
||||
url_given = True
|
||||
elif host.lower().startswith('ldapi://') and unix_socket_available:
|
||||
self.ipc = True
|
||||
use_ssl = False
|
||||
url_given = True
|
||||
elif host.lower().startswith('ldapi://') and not unix_socket_available:
|
||||
raise LDAPSocketOpenError('LDAP over IPC not available - UNIX sockets non present')
|
||||
else:
|
||||
self.host = host
|
||||
|
||||
if self.ipc:
|
||||
if str is bytes: # Python 2
|
||||
self.host = unquote(host[7:]).decode('utf-8')
|
||||
else: # Python 3
|
||||
self.host = unquote(host[7:]) # encoding defaults to utf-8 in python3
|
||||
self.port = None
|
||||
elif ':' in self.host and self.host.count(':') == 1:
|
||||
hostname, _, hostport = self.host.partition(':')
|
||||
try:
|
||||
port = int(hostport) or port
|
||||
except ValueError:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'port <%s> must be an integer', port)
|
||||
raise LDAPInvalidPortError('port must be an integer')
|
||||
self.host = hostname
|
||||
elif url_given and self.host.startswith('['):
|
||||
hostname, sep, hostport = self.host[1:].partition(']')
|
||||
if sep != ']' or not self._is_ipv6(hostname):
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid IPv6 server address for <%s>', self.host)
|
||||
raise LDAPInvalidServerError()
|
||||
if len(hostport):
|
||||
if not hostport.startswith(':'):
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid URL in server name for <%s>', self.host)
|
||||
raise LDAPInvalidServerError('invalid URL in server name')
|
||||
if not hostport[1:].isdecimal():
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'port must be an integer for <%s>', self.host)
|
||||
raise LDAPInvalidPortError('port must be an integer')
|
||||
port = int(hostport[1:])
|
||||
self.host = hostname
|
||||
elif not url_given and self._is_ipv6(self.host):
|
||||
pass
|
||||
elif self.host.count(':') > 1:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid server address for <%s>', self.host)
|
||||
raise LDAPInvalidServerError()
|
||||
|
||||
if not self.ipc:
|
||||
self.host.rstrip('/')
|
||||
if not use_ssl and not port:
|
||||
port = 389
|
||||
elif use_ssl and not port:
|
||||
port = 636
|
||||
|
||||
port_err = check_port(port)
|
||||
if port_err:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, port_err)
|
||||
raise LDAPInvalidPortError(port_err)
|
||||
self.port = port
|
||||
|
||||
if allowed_referral_hosts is None: # defaults to any server with authentication
|
||||
allowed_referral_hosts = [('*', True)]
|
||||
|
||||
if isinstance(allowed_referral_hosts, SEQUENCE_TYPES):
|
||||
self.allowed_referral_hosts = []
|
||||
for referral_host in allowed_referral_hosts:
|
||||
if isinstance(referral_host, tuple):
|
||||
if isinstance(referral_host[1], bool):
|
||||
self.allowed_referral_hosts.append(referral_host)
|
||||
elif isinstance(allowed_referral_hosts, tuple):
|
||||
if isinstance(allowed_referral_hosts[1], bool):
|
||||
self.allowed_referral_hosts = [allowed_referral_hosts]
|
||||
else:
|
||||
self.allowed_referral_hosts = []
|
||||
|
||||
self.ssl = True if use_ssl else False
|
||||
if tls and not isinstance(tls, Tls):
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid tls specification: <%s>', tls)
|
||||
raise LDAPInvalidTlsSpecificationError('invalid Tls object')
|
||||
|
||||
self.tls = Tls() if self.ssl and not tls else tls
|
||||
|
||||
if not self.ipc:
|
||||
if self._is_ipv6(self.host):
|
||||
self.name = ('ldaps' if self.ssl else 'ldap') + '://[' + self.host + ']:' + str(self.port)
|
||||
else:
|
||||
self.name = ('ldaps' if self.ssl else 'ldap') + '://' + self.host + ':' + str(self.port)
|
||||
else:
|
||||
self.name = host
|
||||
|
||||
self.get_info = get_info
|
||||
self._dsa_info = None
|
||||
self._schema_info = None
|
||||
self.dit_lock = Lock()
|
||||
self.custom_formatter = formatter
|
||||
self.custom_validator = validator
|
||||
self._address_info = [] # property self.address_info resolved at open time (or when check_availability is called)
|
||||
self._address_info_resolved_time = datetime(MINYEAR, 1, 1) # smallest date ever
|
||||
self.current_address = None
|
||||
self.connect_timeout = connect_timeout
|
||||
self.mode = mode
|
||||
|
||||
self.get_info_from_server(None) # load offline schema if needed
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated Server: <%r>', self)
|
||||
|
||||
@staticmethod
|
||||
def _is_ipv6(host):
|
||||
try:
|
||||
socket.inet_pton(socket.AF_INET6, host)
|
||||
except (socket.error, AttributeError, ValueError):
|
||||
return False
|
||||
return True
|
||||
|
||||
def __str__(self):
|
||||
if self.host:
|
||||
s = self.name + (' - ssl' if self.ssl else ' - cleartext') + (' - unix socket' if self.ipc else '')
|
||||
else:
|
||||
s = object.__str__(self)
|
||||
return s
|
||||
|
||||
def __repr__(self):
|
||||
r = 'Server(host={0.host!r}, port={0.port!r}, use_ssl={0.ssl!r}'.format(self)
|
||||
r += '' if not self.allowed_referral_hosts else ', allowed_referral_hosts={0.allowed_referral_hosts!r}'.format(self)
|
||||
r += '' if self.tls is None else ', tls={0.tls!r}'.format(self)
|
||||
r += '' if not self.get_info else ', get_info={0.get_info!r}'.format(self)
|
||||
r += '' if not self.connect_timeout else ', connect_timeout={0.connect_timeout!r}'.format(self)
|
||||
r += '' if not self.mode else ', mode={0.mode!r}'.format(self)
|
||||
r += ')'
|
||||
|
||||
return r
|
||||
|
||||
@property
|
||||
def address_info(self):
|
||||
conf_refresh_interval = get_config_parameter('ADDRESS_INFO_REFRESH_TIME')
|
||||
if not self._address_info or (datetime.now() - self._address_info_resolved_time).seconds > conf_refresh_interval:
|
||||
# converts addresses tuple to list and adds a 6th parameter for availability (None = not checked, True = available, False=not available) and a 7th parameter for the checking time
|
||||
addresses = None
|
||||
try:
|
||||
if self.ipc:
|
||||
addresses = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, None, self.host, None)]
|
||||
else:
|
||||
if self.mode == IP_V4_ONLY:
|
||||
addresses = socket.getaddrinfo(self.host, self.port, socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED)
|
||||
elif self.mode == IP_V6_ONLY:
|
||||
addresses = socket.getaddrinfo(self.host, self.port, socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED)
|
||||
else:
|
||||
addresses = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED)
|
||||
except (socket.gaierror, AttributeError):
|
||||
pass
|
||||
|
||||
if not addresses: # if addresses not found or raised an exception (for example for bad flags) tries again without flags
|
||||
try:
|
||||
if self.mode == IP_V4_ONLY:
|
||||
addresses = socket.getaddrinfo(self.host, self.port, socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
|
||||
elif self.mode == IP_V6_ONLY:
|
||||
addresses = socket.getaddrinfo(self.host, self.port, socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP)
|
||||
else:
|
||||
addresses = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP)
|
||||
except socket.gaierror:
|
||||
pass
|
||||
|
||||
if addresses:
|
||||
self._address_info = [list(address) + [None, None] for address in addresses]
|
||||
self._address_info_resolved_time = datetime.now()
|
||||
else:
|
||||
self._address_info = []
|
||||
self._address_info_resolved_time = datetime(MINYEAR, 1, 1) # smallest date
|
||||
|
||||
if log_enabled(BASIC):
|
||||
for address in self._address_info:
|
||||
log(BASIC, 'address for <%s> resolved as <%r>', self, address[:-2])
|
||||
return self._address_info
|
||||
|
||||
def update_availability(self, address, available):
|
||||
cont = 0
|
||||
while cont < len(self._address_info):
|
||||
if self.address_info[cont] == address:
|
||||
self._address_info[cont][5] = True if available else False
|
||||
self._address_info[cont][6] = datetime.now()
|
||||
break
|
||||
cont += 1
|
||||
|
||||
def reset_availability(self):
|
||||
for address in self._address_info:
|
||||
address[5] = None
|
||||
address[6] = None
|
||||
|
||||
def check_availability(self, source_address=None, source_port=None, source_port_list=None):
|
||||
"""
|
||||
Tries to open, connect and close a socket to specified address and port to check availability.
|
||||
Timeout in seconds is specified in CHECK_AVAILABITY_TIMEOUT if not specified in
|
||||
the Server object.
|
||||
If specified, use a specific address, port, or list of possible ports, when attempting to check availability.
|
||||
NOTE: This will only consider multiple ports from the source port list if the first ones we try to bind to are
|
||||
already in use. This will not attempt using different ports in the list if the server is unavailable,
|
||||
as that could result in the runtime of check_availability significantly exceeding the connection timeout.
|
||||
"""
|
||||
source_port_err = check_port_and_port_list(source_port, source_port_list)
|
||||
if source_port_err:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, source_port_err)
|
||||
raise LDAPInvalidPortError(source_port_err)
|
||||
|
||||
# using an empty string to bind a socket means "use the default as if this wasn't provided" because socket
|
||||
# binding requires that you pass something for the ip if you want to pass a specific port
|
||||
bind_address = source_address if source_address is not None else ''
|
||||
# using 0 as the source port to bind a socket means "use the default behavior of picking a random port from
|
||||
# all ports as if this wasn't provided" because socket binding requires that you pass something for the port
|
||||
# if you want to pass a specific ip
|
||||
candidate_bind_ports = [0]
|
||||
|
||||
# if we have either a source port or source port list, convert that into our candidate list
|
||||
if source_port is not None:
|
||||
candidate_bind_ports = [source_port]
|
||||
elif source_port_list is not None:
|
||||
candidate_bind_ports = source_port_list[:]
|
||||
|
||||
conf_availability_timeout = get_config_parameter('CHECK_AVAILABILITY_TIMEOUT')
|
||||
available = False
|
||||
self.reset_availability()
|
||||
for address in self.candidate_addresses():
|
||||
available = True
|
||||
try:
|
||||
temp_socket = socket.socket(*address[:3])
|
||||
|
||||
# Go through our candidate bind ports and try to bind our socket to our source address with them.
|
||||
# if no source address or ports were specified, this will have the same success/fail result as if we
|
||||
# tried to connect to the remote server without binding locally first.
|
||||
# This is actually a little bit better, as it lets us distinguish the case of "issue binding the socket
|
||||
# locally" from "remote server is unavailable" with more clarity, though this will only really be an
|
||||
# issue when no source address/port is specified if the system checking server availability is running
|
||||
# as a very unprivileged user.
|
||||
last_bind_exc = None
|
||||
socket_bind_succeeded = False
|
||||
for bind_port in candidate_bind_ports:
|
||||
try:
|
||||
temp_socket.bind((bind_address, bind_port))
|
||||
socket_bind_succeeded = True
|
||||
break
|
||||
except Exception as bind_ex:
|
||||
last_bind_exc = bind_ex
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'Unable to bind to local address <%s> with source port <%s> due to <%s>',
|
||||
bind_address, bind_port, bind_ex)
|
||||
if not socket_bind_succeeded:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'Unable to locally bind to local address <%s> with any of the source ports <%s> due to <%s>',
|
||||
bind_address, candidate_bind_ports, last_bind_exc)
|
||||
raise LDAPSocketOpenError('Unable to bind socket locally to address {} with any of the source ports {} due to {}'
|
||||
.format(bind_address, candidate_bind_ports, last_bind_exc))
|
||||
|
||||
if self.connect_timeout:
|
||||
temp_socket.settimeout(self.connect_timeout)
|
||||
else:
|
||||
temp_socket.settimeout(conf_availability_timeout) # set timeout for checking availability to default
|
||||
try:
|
||||
temp_socket.connect(address[4])
|
||||
except socket.error:
|
||||
available = False
|
||||
finally:
|
||||
try:
|
||||
temp_socket.shutdown(socket.SHUT_RDWR)
|
||||
except socket.error:
|
||||
available = False
|
||||
finally:
|
||||
temp_socket.close()
|
||||
except socket.gaierror:
|
||||
available = False
|
||||
|
||||
if available:
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'server <%s> available at <%r>', self, address)
|
||||
self.update_availability(address, True)
|
||||
break # if an available address is found exits immediately
|
||||
else:
|
||||
self.update_availability(address, False)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'server <%s> not available at <%r>', self, address)
|
||||
|
||||
return available
|
||||
|
||||
@staticmethod
|
||||
def next_message_id():
|
||||
"""
|
||||
LDAP messageId is unique for all connections to same server
|
||||
"""
|
||||
with Server._message_id_lock:
|
||||
Server._message_counter += 1
|
||||
if Server._message_counter >= LDAP_MAX_INT:
|
||||
Server._message_counter = 1
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'new message id <%d> generated', Server._message_counter)
|
||||
|
||||
return Server._message_counter
|
||||
|
||||
def _get_dsa_info(self, connection):
|
||||
"""
|
||||
Retrieve DSE operational attribute as per RFC4512 (5.1).
|
||||
"""
|
||||
if connection.strategy.no_real_dsa: # do not try for mock strategies
|
||||
return
|
||||
|
||||
if not connection.strategy.pooled: # in pooled strategies get_dsa_info is performed by the worker threads
|
||||
result = connection.search(search_base='',
|
||||
search_filter='(objectClass=*)',
|
||||
search_scope=BASE,
|
||||
attributes=['altServer', # requests specific dsa info attributes
|
||||
'namingContexts',
|
||||
'supportedControl',
|
||||
'supportedExtension',
|
||||
'supportedFeatures',
|
||||
'supportedCapabilities',
|
||||
'supportedLdapVersion',
|
||||
'supportedSASLMechanisms',
|
||||
'vendorName',
|
||||
'vendorVersion',
|
||||
'subschemaSubentry',
|
||||
'*',
|
||||
'+'], # requests all remaining attributes (other),
|
||||
get_operational_attributes=True)
|
||||
|
||||
if connection.strategy.thread_safe:
|
||||
status, result, response, _ = result
|
||||
else:
|
||||
status = result
|
||||
result = connection.result
|
||||
response = connection.response
|
||||
|
||||
with self.dit_lock:
|
||||
if connection.strategy.sync: # sync request
|
||||
self._dsa_info = DsaInfo(response[0]['attributes'], response[0]['raw_attributes']) if status else self._dsa_info
|
||||
elif status: # asynchronous request, must check if attributes in response
|
||||
results, _ = connection.get_response(status)
|
||||
if len(results) == 1 and 'attributes' in results[0] and 'raw_attributes' in results[0]:
|
||||
self._dsa_info = DsaInfo(results[0]['attributes'], results[0]['raw_attributes'])
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'DSA info read for <%s> via <%s>', self, connection)
|
||||
|
||||
def _get_schema_info(self, connection, entry=''):
|
||||
"""
|
||||
Retrieve schema from subschemaSubentry DSE attribute, per RFC
|
||||
4512 (4.4 and 5.1); entry = '' means DSE.
|
||||
"""
|
||||
if connection.strategy.no_real_dsa: # do not try for mock strategies
|
||||
return
|
||||
|
||||
schema_entry = None
|
||||
if self._dsa_info and entry == '': # subschemaSubentry already present in dsaInfo
|
||||
if isinstance(self._dsa_info.schema_entry, SEQUENCE_TYPES):
|
||||
schema_entry = self._dsa_info.schema_entry[0] if self._dsa_info.schema_entry else None
|
||||
else:
|
||||
schema_entry = self._dsa_info.schema_entry if self._dsa_info.schema_entry else None
|
||||
else:
|
||||
result = connection.search(entry, '(objectClass=*)', BASE, attributes=['subschemaSubentry'], get_operational_attributes=True)
|
||||
if connection.strategy.thread_safe:
|
||||
status, result, response, _ = result
|
||||
else:
|
||||
status = result
|
||||
result = connection.result
|
||||
response = connection.response
|
||||
if connection.strategy.sync: # sync request
|
||||
if status and 'subschemaSubentry' in response[0]['raw_attributes']:
|
||||
if len(response[0]['raw_attributes']['subschemaSubentry']) > 0:
|
||||
schema_entry = response[0]['raw_attributes']['subschemaSubentry'][0]
|
||||
else: # asynchronous request, must check if subschemaSubentry in attributes
|
||||
results, _ = connection.get_response(status)
|
||||
if len(results) == 1 and 'raw_attributes' in results[0] and 'subschemaSubentry' in results[0]['attributes']:
|
||||
if len(results[0]['raw_attributes']['subschemaSubentry']) > 0:
|
||||
schema_entry = results[0]['raw_attributes']['subschemaSubentry'][0]
|
||||
|
||||
if schema_entry and not connection.strategy.pooled: # in pooled strategies get_schema_info is performed by the worker threads
|
||||
if isinstance(schema_entry, bytes) and str is not bytes: # Python 3
|
||||
schema_entry = to_unicode(schema_entry, from_server=True)
|
||||
result = connection.search(schema_entry,
|
||||
search_filter='(objectClass=subschema)',
|
||||
search_scope=BASE,
|
||||
attributes=['objectClasses', # requests specific subschema attributes
|
||||
'attributeTypes',
|
||||
'ldapSyntaxes',
|
||||
'matchingRules',
|
||||
'matchingRuleUse',
|
||||
'dITContentRules',
|
||||
'dITStructureRules',
|
||||
'nameForms',
|
||||
'createTimestamp',
|
||||
'modifyTimestamp',
|
||||
'*'], # requests all remaining attributes (other)
|
||||
get_operational_attributes=True
|
||||
)
|
||||
if connection.strategy.thread_safe:
|
||||
status, result, response, _ = result
|
||||
else:
|
||||
status = result
|
||||
result = connection.result
|
||||
response = connection.response
|
||||
with self.dit_lock:
|
||||
self._schema_info = None
|
||||
if status:
|
||||
if connection.strategy.sync: # sync request
|
||||
self._schema_info = SchemaInfo(schema_entry, response[0]['attributes'], response[0]['raw_attributes'])
|
||||
else: # asynchronous request, must check if attributes in response
|
||||
results, result = connection.get_response(status)
|
||||
if len(results) == 1 and 'attributes' in results[0] and 'raw_attributes' in results[0]:
|
||||
self._schema_info = SchemaInfo(schema_entry, results[0]['attributes'], results[0]['raw_attributes'])
|
||||
if self._schema_info and not self._schema_info.is_valid(): # flaky servers can return an empty schema, checks if it is so and set schema to None
|
||||
self._schema_info = None
|
||||
if self._schema_info: # if schema is valid tries to apply formatter to the "other" dict with raw values for schema and info
|
||||
for attribute in self._schema_info.other:
|
||||
self._schema_info.other[attribute] = format_attribute_values(self._schema_info, attribute, self._schema_info.raw[attribute], self.custom_formatter)
|
||||
if self._dsa_info: # try to apply formatter to the "other" dict with dsa info raw values
|
||||
for attribute in self._dsa_info.other:
|
||||
self._dsa_info.other[attribute] = format_attribute_values(self._schema_info, attribute, self._dsa_info.raw[attribute], self.custom_formatter)
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'schema read for <%s> via <%s>', self, connection)
|
||||
|
||||
def get_info_from_server(self, connection):
|
||||
"""
|
||||
reads info from DSE and from subschema
|
||||
"""
|
||||
if connection and not connection.closed:
|
||||
if self.get_info in [DSA, ALL]:
|
||||
self._get_dsa_info(connection)
|
||||
if self.get_info in [SCHEMA, ALL]:
|
||||
self._get_schema_info(connection)
|
||||
elif self.get_info == OFFLINE_EDIR_8_8_8:
|
||||
from ..protocol.schemas.edir888 import edir_8_8_8_schema, edir_8_8_8_dsa_info
|
||||
self.attach_schema_info(SchemaInfo.from_json(edir_8_8_8_schema))
|
||||
self.attach_dsa_info(DsaInfo.from_json(edir_8_8_8_dsa_info))
|
||||
elif self.get_info == OFFLINE_EDIR_9_1_4:
|
||||
from ..protocol.schemas.edir914 import edir_9_1_4_schema, edir_9_1_4_dsa_info
|
||||
self.attach_schema_info(SchemaInfo.from_json(edir_9_1_4_schema))
|
||||
self.attach_dsa_info(DsaInfo.from_json(edir_9_1_4_dsa_info))
|
||||
elif self.get_info == OFFLINE_AD_2012_R2:
|
||||
from ..protocol.schemas.ad2012R2 import ad_2012_r2_schema, ad_2012_r2_dsa_info
|
||||
self.attach_schema_info(SchemaInfo.from_json(ad_2012_r2_schema))
|
||||
self.attach_dsa_info(DsaInfo.from_json(ad_2012_r2_dsa_info))
|
||||
elif self.get_info == OFFLINE_SLAPD_2_4:
|
||||
from ..protocol.schemas.slapd24 import slapd_2_4_schema, slapd_2_4_dsa_info
|
||||
self.attach_schema_info(SchemaInfo.from_json(slapd_2_4_schema))
|
||||
self.attach_dsa_info(DsaInfo.from_json(slapd_2_4_dsa_info))
|
||||
elif self.get_info == OFFLINE_DS389_1_3_3:
|
||||
from ..protocol.schemas.ds389 import ds389_1_3_3_schema, ds389_1_3_3_dsa_info
|
||||
self.attach_schema_info(SchemaInfo.from_json(ds389_1_3_3_schema))
|
||||
self.attach_dsa_info(DsaInfo.from_json(ds389_1_3_3_dsa_info))
|
||||
|
||||
def attach_dsa_info(self, dsa_info=None):
|
||||
if isinstance(dsa_info, DsaInfo):
|
||||
self._dsa_info = dsa_info
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'attached DSA info to Server <%s>', self)
|
||||
|
||||
def attach_schema_info(self, dsa_schema=None):
|
||||
if isinstance(dsa_schema, SchemaInfo):
|
||||
self._schema_info = dsa_schema
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'attached schema info to Server <%s>', self)
|
||||
|
||||
@property
|
||||
def info(self):
|
||||
return self._dsa_info
|
||||
|
||||
@property
|
||||
def schema(self):
|
||||
return self._schema_info
|
||||
|
||||
@staticmethod
|
||||
def from_definition(host, dsa_info, dsa_schema, port=None, use_ssl=False, formatter=None, validator=None):
|
||||
"""
|
||||
Define a dummy server with preloaded schema and info
|
||||
:param host: host name
|
||||
:param dsa_info: DsaInfo preloaded object or a json formatted string or a file name
|
||||
:param dsa_schema: SchemaInfo preloaded object or a json formatted string or a file name
|
||||
:param port: fake port
|
||||
:param use_ssl: use_ssl
|
||||
:param formatter: custom formatters
|
||||
:return: Server object
|
||||
"""
|
||||
if isinstance(host, SEQUENCE_TYPES):
|
||||
dummy = Server(host=host[0], port=port, use_ssl=use_ssl, formatter=formatter, validator=validator, get_info=ALL) # for ServerPool object
|
||||
else:
|
||||
dummy = Server(host=host, port=port, use_ssl=use_ssl, formatter=formatter, validator=validator, get_info=ALL)
|
||||
if isinstance(dsa_info, DsaInfo):
|
||||
dummy._dsa_info = dsa_info
|
||||
elif isinstance(dsa_info, STRING_TYPES):
|
||||
try:
|
||||
dummy._dsa_info = DsaInfo.from_json(dsa_info) # tries to use dsa_info as a json configuration string
|
||||
except Exception:
|
||||
dummy._dsa_info = DsaInfo.from_file(dsa_info) # tries to use dsa_info as a file name
|
||||
|
||||
if not dummy.info:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid DSA info for %s', host)
|
||||
raise LDAPDefinitionError('invalid dsa info')
|
||||
|
||||
if isinstance(dsa_schema, SchemaInfo):
|
||||
dummy._schema_info = dsa_schema
|
||||
elif isinstance(dsa_schema, STRING_TYPES):
|
||||
try:
|
||||
dummy._schema_info = SchemaInfo.from_json(dsa_schema)
|
||||
except Exception:
|
||||
dummy._schema_info = SchemaInfo.from_file(dsa_schema)
|
||||
|
||||
if not dummy.schema:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid schema info for %s', host)
|
||||
raise LDAPDefinitionError('invalid schema info')
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'created server <%s> from definition', dummy)
|
||||
|
||||
return dummy
|
||||
|
||||
def candidate_addresses(self):
|
||||
conf_reset_availability_timeout = get_config_parameter('RESET_AVAILABILITY_TIMEOUT')
|
||||
if self.ipc:
|
||||
candidates = self.address_info
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'candidate address for <%s>: <%s> with mode UNIX_SOCKET', self, self.name)
|
||||
else:
|
||||
# checks reset availability timeout
|
||||
for address in self.address_info:
|
||||
if address[6] and ((datetime.now() - address[6]).seconds > conf_reset_availability_timeout):
|
||||
address[5] = None
|
||||
address[6] = None
|
||||
|
||||
# selects server address based on server mode and availability (in address[5])
|
||||
addresses = self.address_info[:] # copy to avoid refreshing while searching candidates
|
||||
candidates = []
|
||||
if addresses:
|
||||
if self.mode == IP_SYSTEM_DEFAULT:
|
||||
candidates.append(addresses[0])
|
||||
elif self.mode == IP_V4_ONLY:
|
||||
candidates = [address for address in addresses if address[0] == socket.AF_INET and (address[5] or address[5] is None)]
|
||||
elif self.mode == IP_V6_ONLY:
|
||||
candidates = [address for address in addresses if address[0] == socket.AF_INET6 and (address[5] or address[5] is None)]
|
||||
elif self.mode == IP_V4_PREFERRED:
|
||||
candidates = [address for address in addresses if address[0] == socket.AF_INET and (address[5] or address[5] is None)]
|
||||
candidates += [address for address in addresses if address[0] == socket.AF_INET6 and (address[5] or address[5] is None)]
|
||||
elif self.mode == IP_V6_PREFERRED:
|
||||
candidates = [address for address in addresses if address[0] == socket.AF_INET6 and (address[5] or address[5] is None)]
|
||||
candidates += [address for address in addresses if address[0] == socket.AF_INET and (address[5] or address[5] is None)]
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid server mode for <%s>', self)
|
||||
raise LDAPInvalidServerError('invalid server mode')
|
||||
|
||||
if log_enabled(BASIC):
|
||||
for candidate in candidates:
|
||||
log(BASIC, 'obtained candidate address for <%s>: <%r> with mode %s', self, candidate[:-2], self.mode)
|
||||
return candidates
|
||||
|
||||
def _check_info_property(self, kind, name):
|
||||
if not self._dsa_info:
|
||||
raise LDAPInfoError('server info not loaded')
|
||||
|
||||
if kind == 'control':
|
||||
properties = self.info.supported_controls
|
||||
elif kind == 'extension':
|
||||
properties = self.info.supported_extensions
|
||||
elif kind == 'feature':
|
||||
properties = self.info.supported_features
|
||||
else:
|
||||
raise LDAPInfoError('invalid info category')
|
||||
|
||||
for prop in properties:
|
||||
if name == prop[0] or (prop[2] and name.lower() == prop[2].lower()): # checks oid and description
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def has_control(self, control):
|
||||
return self._check_info_property('control', control)
|
||||
|
||||
def has_extension(self, extension):
|
||||
return self._check_info_property('extension', extension)
|
||||
|
||||
def has_feature(self, feature):
|
||||
return self._check_info_property('feature', feature)
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2015.01.07
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2015 - 2020 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 datetime import timedelta, tzinfo
|
||||
|
||||
|
||||
# from python standard library docs
|
||||
class OffsetTzInfo(tzinfo):
|
||||
"""Fixed offset in minutes east from UTC"""
|
||||
|
||||
def __init__(self, offset, name):
|
||||
self.offset = offset
|
||||
self.name = name
|
||||
self._offset = timedelta(minutes=offset)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def __repr__(self):
|
||||
|
||||
return 'OffsetTzInfo(offset={0.offset!r}, name={0.name!r})'.format(self)
|
||||
|
||||
def utcoffset(self, dt):
|
||||
return self._offset
|
||||
|
||||
def tzname(self, dt):
|
||||
return self.name
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def dst(self, dt):
|
||||
return timedelta(0)
|
||||
|
||||
def __getinitargs__(self): # for pickling/unpickling
|
||||
return self.offset, self.name
|
|
@ -0,0 +1,327 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2013.08.05
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2013 - 2020 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 .exceptions import LDAPSSLNotSupportedError, LDAPSSLConfigurationError, LDAPCertificateError, start_tls_exception_factory, LDAPStartTLSError
|
||||
from .. import SEQUENCE_TYPES
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC, NETWORK
|
||||
|
||||
try:
|
||||
# noinspection PyUnresolvedReferences
|
||||
import ssl
|
||||
except ImportError:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'SSL not supported in this Python interpreter')
|
||||
raise LDAPSSLNotSupportedError('SSL not supported in this Python interpreter')
|
||||
|
||||
try:
|
||||
from ssl import match_hostname, CertificateError # backport for python2 missing ssl functionalities
|
||||
except ImportError:
|
||||
from ..utils.tls_backport import CertificateError
|
||||
from ..utils.tls_backport import match_hostname
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'using tls_backport')
|
||||
|
||||
try: # try to use SSLContext
|
||||
# noinspection PyUnresolvedReferences
|
||||
from ssl import create_default_context, Purpose # defined in Python 3.4 and Python 2.7.9
|
||||
use_ssl_context = True
|
||||
except ImportError:
|
||||
use_ssl_context = False
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'SSLContext unavailable')
|
||||
|
||||
from os import path
|
||||
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
class Tls(object):
|
||||
"""
|
||||
tls/ssl configuration for Server object
|
||||
Starting from python 2.7.9 and python 3.4 uses the SSLContext object
|
||||
that tries to read the CAs defined at system level
|
||||
ca_certs_path and ca_certs_data are valid only when using SSLContext
|
||||
local_private_key_password is valid only when using SSLContext
|
||||
ssl_options is valid only when using SSLContext
|
||||
sni is the server name for Server Name Indication (when available)
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
local_private_key_file=None,
|
||||
local_certificate_file=None,
|
||||
validate=ssl.CERT_NONE,
|
||||
version=None,
|
||||
ssl_options=None,
|
||||
ca_certs_file=None,
|
||||
valid_names=None,
|
||||
ca_certs_path=None,
|
||||
ca_certs_data=None,
|
||||
local_private_key_password=None,
|
||||
ciphers=None,
|
||||
sni=None):
|
||||
if ssl_options is None:
|
||||
ssl_options = []
|
||||
self.ssl_options = ssl_options
|
||||
if validate in [ssl.CERT_NONE, ssl.CERT_OPTIONAL, ssl.CERT_REQUIRED]:
|
||||
self.validate = validate
|
||||
elif validate:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid validate parameter <%s>', validate)
|
||||
raise LDAPSSLConfigurationError('invalid validate parameter')
|
||||
if ca_certs_file and path.exists(ca_certs_file):
|
||||
self.ca_certs_file = ca_certs_file
|
||||
elif ca_certs_file:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid CA public key file <%s>', ca_certs_file)
|
||||
raise LDAPSSLConfigurationError('invalid CA public key file')
|
||||
else:
|
||||
self.ca_certs_file = None
|
||||
|
||||
if ca_certs_path and use_ssl_context and path.exists(ca_certs_path):
|
||||
self.ca_certs_path = ca_certs_path
|
||||
elif ca_certs_path and not use_ssl_context:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'cannot use CA public keys path, SSLContext not available')
|
||||
raise LDAPSSLNotSupportedError('cannot use CA public keys path, SSLContext not available')
|
||||
elif ca_certs_path:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'invalid CA public keys path <%s>', ca_certs_path)
|
||||
raise LDAPSSLConfigurationError('invalid CA public keys path')
|
||||
else:
|
||||
self.ca_certs_path = None
|
||||
|
||||
if ca_certs_data and use_ssl_context:
|
||||
self.ca_certs_data = ca_certs_data
|
||||
elif ca_certs_data:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'cannot use CA data, SSLContext not available')
|
||||
raise LDAPSSLNotSupportedError('cannot use CA data, SSLContext not available')
|
||||
else:
|
||||
self.ca_certs_data = None
|
||||
|
||||
if local_private_key_password and use_ssl_context:
|
||||
self.private_key_password = local_private_key_password
|
||||
elif local_private_key_password:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'cannot use local private key password, SSLContext not available')
|
||||
raise LDAPSSLNotSupportedError('cannot use local private key password, SSLContext is not available')
|
||||
else:
|
||||
self.private_key_password = None
|
||||
|
||||
self.version = version
|
||||
self.private_key_file = local_private_key_file
|
||||
self.certificate_file = local_certificate_file
|
||||
self.valid_names = valid_names
|
||||
self.ciphers = ciphers
|
||||
self.sni = sni
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated Tls: <%r>' % self)
|
||||
|
||||
def __str__(self):
|
||||
s = [
|
||||
'protocol: ' + str(self.version),
|
||||
'client private key: ' + ('present ' if self.private_key_file else 'not present'),
|
||||
'client certificate: ' + ('present ' if self.certificate_file else 'not present'),
|
||||
'private key password: ' + ('present ' if self.private_key_password else 'not present'),
|
||||
'CA certificates file: ' + ('present ' if self.ca_certs_file else 'not present'),
|
||||
'CA certificates path: ' + ('present ' if self.ca_certs_path else 'not present'),
|
||||
'CA certificates data: ' + ('present ' if self.ca_certs_data else 'not present'),
|
||||
'verify mode: ' + str(self.validate),
|
||||
'valid names: ' + str(self.valid_names),
|
||||
'ciphers: ' + str(self.ciphers),
|
||||
'sni: ' + str(self.sni)
|
||||
]
|
||||
return ' - '.join(s)
|
||||
|
||||
def __repr__(self):
|
||||
r = '' if self.private_key_file is None else ', local_private_key_file={0.private_key_file!r}'.format(self)
|
||||
r += '' if self.certificate_file is None else ', local_certificate_file={0.certificate_file!r}'.format(self)
|
||||
r += '' if self.validate is None else ', validate={0.validate!r}'.format(self)
|
||||
r += '' if self.version is None else ', version={0.version!r}'.format(self)
|
||||
r += '' if self.ca_certs_file is None else ', ca_certs_file={0.ca_certs_file!r}'.format(self)
|
||||
r += '' if self.ca_certs_path is None else ', ca_certs_path={0.ca_certs_path!r}'.format(self)
|
||||
r += '' if self.ca_certs_data is None else ', ca_certs_data={0.ca_certs_data!r}'.format(self)
|
||||
r += '' if self.ciphers is None else ', ciphers={0.ciphers!r}'.format(self)
|
||||
r += '' if self.sni is None else ', sni={0.sni!r}'.format(self)
|
||||
r = 'Tls(' + r[2:] + ')'
|
||||
return r
|
||||
|
||||
def wrap_socket(self, connection, do_handshake=False):
|
||||
"""
|
||||
Adds TLS to the connection socket
|
||||
"""
|
||||
if use_ssl_context:
|
||||
if self.version is None: # uses the default ssl context for reasonable security
|
||||
ssl_context = create_default_context(purpose=Purpose.SERVER_AUTH,
|
||||
cafile=self.ca_certs_file,
|
||||
capath=self.ca_certs_path,
|
||||
cadata=self.ca_certs_data)
|
||||
else: # code from create_default_context in the Python standard library 3.5.1, creates a ssl context with the specificd protocol version
|
||||
ssl_context = ssl.SSLContext(self.version)
|
||||
if self.ca_certs_file or self.ca_certs_path or self.ca_certs_data:
|
||||
ssl_context.load_verify_locations(self.ca_certs_file, self.ca_certs_path, self.ca_certs_data)
|
||||
elif self.validate != ssl.CERT_NONE:
|
||||
ssl_context.load_default_certs(Purpose.SERVER_AUTH)
|
||||
|
||||
if self.certificate_file:
|
||||
ssl_context.load_cert_chain(self.certificate_file, keyfile=self.private_key_file, password=self.private_key_password)
|
||||
ssl_context.check_hostname = False
|
||||
ssl_context.verify_mode = self.validate
|
||||
for option in self.ssl_options:
|
||||
ssl_context.options |= option
|
||||
|
||||
if self.ciphers:
|
||||
try:
|
||||
ssl_context.set_ciphers(self.ciphers)
|
||||
except ssl.SSLError:
|
||||
pass
|
||||
|
||||
if self.sni:
|
||||
wrapped_socket = ssl_context.wrap_socket(connection.socket, server_side=False, do_handshake_on_connect=do_handshake, server_hostname=self.sni)
|
||||
else:
|
||||
wrapped_socket = ssl_context.wrap_socket(connection.socket, server_side=False, do_handshake_on_connect=do_handshake)
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'socket wrapped with SSL using SSLContext for <%s>', connection)
|
||||
else:
|
||||
if self.version is None and hasattr(ssl, 'PROTOCOL_SSLv23'):
|
||||
self.version = ssl.PROTOCOL_SSLv23
|
||||
if self.ciphers:
|
||||
try:
|
||||
|
||||
wrapped_socket = ssl.wrap_socket(connection.socket,
|
||||
keyfile=self.private_key_file,
|
||||
certfile=self.certificate_file,
|
||||
server_side=False,
|
||||
cert_reqs=self.validate,
|
||||
ssl_version=self.version,
|
||||
ca_certs=self.ca_certs_file,
|
||||
do_handshake_on_connect=do_handshake,
|
||||
ciphers=self.ciphers)
|
||||
except ssl.SSLError:
|
||||
raise
|
||||
except TypeError: # in python2.6 no ciphers argument is present, failback to self.ciphers=None
|
||||
self.ciphers = None
|
||||
|
||||
if not self.ciphers:
|
||||
wrapped_socket = ssl.wrap_socket(connection.socket,
|
||||
keyfile=self.private_key_file,
|
||||
certfile=self.certificate_file,
|
||||
server_side=False,
|
||||
cert_reqs=self.validate,
|
||||
ssl_version=self.version,
|
||||
ca_certs=self.ca_certs_file,
|
||||
do_handshake_on_connect=do_handshake)
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'socket wrapped with SSL for <%s>', connection)
|
||||
|
||||
if do_handshake and (self.validate == ssl.CERT_REQUIRED or self.validate == ssl.CERT_OPTIONAL):
|
||||
check_hostname(wrapped_socket, connection.server.host, self.valid_names)
|
||||
|
||||
connection.socket = wrapped_socket
|
||||
return
|
||||
|
||||
def start_tls(self, connection):
|
||||
if connection.server.ssl: # ssl already established at server level
|
||||
return False
|
||||
|
||||
if (connection.tls_started and not connection._executing_deferred) or connection.strategy._outstanding or connection.sasl_in_progress:
|
||||
# Per RFC 4513 (3.1.1)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, "can't start tls because operations are in progress for <%s>", self)
|
||||
return False
|
||||
connection.starting_tls = True
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'starting tls for <%s>', connection)
|
||||
if not connection.strategy.sync:
|
||||
connection._awaiting_for_async_start_tls = True # some flaky servers (OpenLDAP) doesn't return the extended response name in response
|
||||
result = connection.extended('1.3.6.1.4.1.1466.20037')
|
||||
if not connection.strategy.sync:
|
||||
# asynchronous - _start_tls must be executed by the strategy
|
||||
response = connection.get_response(result)
|
||||
if response != (None, None):
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'tls started for <%s>', connection)
|
||||
return True
|
||||
else:
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'tls not started for <%s>', connection)
|
||||
return False
|
||||
else:
|
||||
if connection.result['description'] not in ['success']:
|
||||
# startTLS failed
|
||||
connection.last_error = 'startTLS failed - ' + str(connection.result['description'])
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, '%s for <%s>', connection.last_error, connection)
|
||||
raise LDAPStartTLSError(connection.last_error)
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'tls started for <%s>', connection)
|
||||
return self._start_tls(connection)
|
||||
|
||||
def _start_tls(self, connection):
|
||||
try:
|
||||
self.wrap_socket(connection, do_handshake=True)
|
||||
except Exception as e:
|
||||
connection.last_error = 'wrap socket error: ' + str(e)
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'error <%s> wrapping socket for TLS in <%s>', connection.last_error, connection)
|
||||
raise start_tls_exception_factory(e)(connection.last_error)
|
||||
finally:
|
||||
connection.starting_tls = False
|
||||
|
||||
if connection.usage:
|
||||
connection._usage.wrapped_sockets += 1
|
||||
connection.tls_started = True
|
||||
return True
|
||||
|
||||
|
||||
def check_hostname(sock, server_name, additional_names):
|
||||
server_certificate = sock.getpeercert()
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'certificate found for %s: %s', sock, server_certificate)
|
||||
if additional_names:
|
||||
host_names = [server_name] + (additional_names if isinstance(additional_names, SEQUENCE_TYPES) else [additional_names])
|
||||
else:
|
||||
host_names = [server_name]
|
||||
|
||||
for host_name in host_names:
|
||||
if not host_name:
|
||||
continue
|
||||
elif host_name == '*':
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'certificate matches * wildcard')
|
||||
return # valid
|
||||
|
||||
try:
|
||||
match_hostname(server_certificate, host_name) # raise CertificateError if certificate doesn't match server name
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, 'certificate matches host name <%s>', host_name)
|
||||
return # valid
|
||||
except CertificateError as e:
|
||||
if log_enabled(NETWORK):
|
||||
log(NETWORK, str(e))
|
||||
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, "hostname doesn't match certificate")
|
||||
raise LDAPCertificateError("certificate %s doesn't match any name in %s " % (server_certificate, str(host_names)))
|
|
@ -0,0 +1,229 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.03.15
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2013 - 2020 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 datetime import datetime, timedelta
|
||||
from os import linesep
|
||||
|
||||
from .exceptions import LDAPMetricsError
|
||||
from ..utils.log import log, log_enabled, ERROR, BASIC
|
||||
|
||||
|
||||
class ConnectionUsage(object):
|
||||
"""
|
||||
Collect statistics on connection usage
|
||||
"""
|
||||
|
||||
def reset(self):
|
||||
self.open_sockets = 0
|
||||
self.closed_sockets = 0
|
||||
self.wrapped_sockets = 0
|
||||
self.bytes_transmitted = 0
|
||||
self.bytes_received = 0
|
||||
self.messages_transmitted = 0
|
||||
self.messages_received = 0
|
||||
self.operations = 0
|
||||
self.abandon_operations = 0
|
||||
self.add_operations = 0
|
||||
self.bind_operations = 0
|
||||
self.compare_operations = 0
|
||||
self.delete_operations = 0
|
||||
self.extended_operations = 0
|
||||
self.modify_operations = 0
|
||||
self.modify_dn_operations = 0
|
||||
self.search_operations = 0
|
||||
self.unbind_operations = 0
|
||||
self.referrals_received = 0
|
||||
self.referrals_followed = 0
|
||||
self.referrals_connections = 0
|
||||
self.restartable_failures = 0
|
||||
self.restartable_successes = 0
|
||||
self.servers_from_pool = 0
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'reset usage metrics')
|
||||
|
||||
def __init__(self):
|
||||
self.initial_connection_start_time = None
|
||||
self.open_socket_start_time = None
|
||||
self.connection_stop_time = None
|
||||
self.last_transmitted_time = None
|
||||
self.last_received_time = None
|
||||
self.open_sockets = 0
|
||||
self.closed_sockets = 0
|
||||
self.wrapped_sockets = 0
|
||||
self.bytes_transmitted = 0
|
||||
self.bytes_received = 0
|
||||
self.messages_transmitted = 0
|
||||
self.messages_received = 0
|
||||
self.operations = 0
|
||||
self.abandon_operations = 0
|
||||
self.add_operations = 0
|
||||
self.bind_operations = 0
|
||||
self.compare_operations = 0
|
||||
self.delete_operations = 0
|
||||
self.extended_operations = 0
|
||||
self.modify_operations = 0
|
||||
self.modify_dn_operations = 0
|
||||
self.search_operations = 0
|
||||
self.unbind_operations = 0
|
||||
self.referrals_received = 0
|
||||
self.referrals_followed = 0
|
||||
self.referrals_connections = 0
|
||||
self.restartable_failures = 0
|
||||
self.restartable_successes = 0
|
||||
self.servers_from_pool = 0
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'instantiated Usage object')
|
||||
|
||||
def __repr__(self):
|
||||
r = 'Connection Usage:' + linesep
|
||||
r += ' Time: [elapsed: ' + str(self.elapsed_time) + ']' + linesep
|
||||
r += ' Initial start time: ' + (str(self.initial_connection_start_time.isoformat()) if self.initial_connection_start_time else '') + linesep
|
||||
r += ' Open socket time: ' + (str(self.open_socket_start_time.isoformat()) if self.open_socket_start_time else '') + linesep
|
||||
r += ' Last transmitted time: ' + (str(self.last_transmitted_time.isoformat()) if self.last_transmitted_time else '') + linesep
|
||||
r += ' Last received time: ' + (str(self.last_received_time.isoformat()) if self.last_received_time else '') + linesep
|
||||
r += ' Close socket time: ' + (str(self.connection_stop_time.isoformat()) if self.connection_stop_time else '') + linesep
|
||||
r += ' Server:' + linesep
|
||||
r += ' Servers from pool: ' + str(self.servers_from_pool) + linesep
|
||||
r += ' Sockets open: ' + str(self.open_sockets) + linesep
|
||||
r += ' Sockets closed: ' + str(self.closed_sockets) + linesep
|
||||
r += ' Sockets wrapped: ' + str(self.wrapped_sockets) + linesep
|
||||
r += ' Bytes: ' + str(self.bytes_transmitted + self.bytes_received) + linesep
|
||||
r += ' Transmitted: ' + str(self.bytes_transmitted) + linesep
|
||||
r += ' Received: ' + str(self.bytes_received) + linesep
|
||||
r += ' Messages: ' + str(self.messages_transmitted + self.messages_received) + linesep
|
||||
r += ' Transmitted: ' + str(self.messages_transmitted) + linesep
|
||||
r += ' Received: ' + str(self.messages_received) + linesep
|
||||
r += ' Operations: ' + str(self.operations) + linesep
|
||||
r += ' Abandon: ' + str(self.abandon_operations) + linesep
|
||||
r += ' Bind: ' + str(self.bind_operations) + linesep
|
||||
r += ' Add: ' + str(self.add_operations) + linesep
|
||||
r += ' Compare: ' + str(self.compare_operations) + linesep
|
||||
r += ' Delete: ' + str(self.delete_operations) + linesep
|
||||
r += ' Extended: ' + str(self.extended_operations) + linesep
|
||||
r += ' Modify: ' + str(self.modify_operations) + linesep
|
||||
r += ' ModifyDn: ' + str(self.modify_dn_operations) + linesep
|
||||
r += ' Search: ' + str(self.search_operations) + linesep
|
||||
r += ' Unbind: ' + str(self.unbind_operations) + linesep
|
||||
r += ' Referrals: ' + linesep
|
||||
r += ' Received: ' + str(self.referrals_received) + linesep
|
||||
r += ' Followed: ' + str(self.referrals_followed) + linesep
|
||||
r += ' Connections: ' + str(self.referrals_connections) + linesep
|
||||
r += ' Restartable tries: ' + str(self.restartable_failures + self.restartable_successes) + linesep
|
||||
r += ' Failed restarts: ' + str(self.restartable_failures) + linesep
|
||||
r += ' Successful restarts: ' + str(self.restartable_successes) + linesep
|
||||
return r
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
def __iadd__(self, other):
|
||||
if not isinstance(other, ConnectionUsage):
|
||||
raise LDAPMetricsError('unable to add to ConnectionUsage')
|
||||
|
||||
self.open_sockets += other.open_sockets
|
||||
self.closed_sockets += other.closed_sockets
|
||||
self.wrapped_sockets += other.wrapped_sockets
|
||||
self.bytes_transmitted += other.bytes_transmitted
|
||||
self.bytes_received += other.bytes_received
|
||||
self.messages_transmitted += other.messages_transmitted
|
||||
self.messages_received += other.messages_received
|
||||
self.operations += other.operations
|
||||
self.abandon_operations += other.abandon_operations
|
||||
self.add_operations += other.add_operations
|
||||
self.bind_operations += other.bind_operations
|
||||
self.compare_operations += other.compare_operations
|
||||
self.delete_operations += other.delete_operations
|
||||
self.extended_operations += other.extended_operations
|
||||
self.modify_operations += other.modify_operations
|
||||
self.modify_dn_operations += other.modify_dn_operations
|
||||
self.search_operations += other.search_operations
|
||||
self.unbind_operations += other.unbind_operations
|
||||
self.referrals_received += other.referrals_received
|
||||
self.referrals_followed += other.referrals_followed
|
||||
self.referrals_connections += other.referrals_connections
|
||||
self.restartable_failures += other.restartable_failures
|
||||
self.restartable_successes += other.restartable_successes
|
||||
self.servers_from_pool += other.servers_from_pool
|
||||
return self
|
||||
|
||||
def update_transmitted_message(self, message, length):
|
||||
self.last_transmitted_time = datetime.now()
|
||||
self.bytes_transmitted += length
|
||||
self.operations += 1
|
||||
self.messages_transmitted += 1
|
||||
if message['type'] == 'abandonRequest':
|
||||
self.abandon_operations += 1
|
||||
elif message['type'] == 'addRequest':
|
||||
self.add_operations += 1
|
||||
elif message['type'] == 'bindRequest':
|
||||
self.bind_operations += 1
|
||||
elif message['type'] == 'compareRequest':
|
||||
self.compare_operations += 1
|
||||
elif message['type'] == 'delRequest':
|
||||
self.delete_operations += 1
|
||||
elif message['type'] == 'extendedReq':
|
||||
self.extended_operations += 1
|
||||
elif message['type'] == 'modifyRequest':
|
||||
self.modify_operations += 1
|
||||
elif message['type'] == 'modDNRequest':
|
||||
self.modify_dn_operations += 1
|
||||
elif message['type'] == 'searchRequest':
|
||||
self.search_operations += 1
|
||||
elif message['type'] == 'unbindRequest':
|
||||
self.unbind_operations += 1
|
||||
else:
|
||||
if log_enabled(ERROR):
|
||||
log(ERROR, 'unable to collect usage for unknown message type <%s>', message['type'])
|
||||
raise LDAPMetricsError('unable to collect usage for unknown message type')
|
||||
|
||||
def update_received_message(self, length):
|
||||
self.last_received_time = datetime.now()
|
||||
self.bytes_received += length
|
||||
self.messages_received += 1
|
||||
|
||||
def start(self, reset=True):
|
||||
if reset:
|
||||
self.reset()
|
||||
self.open_socket_start_time = datetime.now()
|
||||
self.connection_stop_time = None
|
||||
if not self.initial_connection_start_time:
|
||||
self.initial_connection_start_time = self.open_socket_start_time
|
||||
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'start collecting usage metrics')
|
||||
|
||||
def stop(self):
|
||||
if self.open_socket_start_time:
|
||||
self.connection_stop_time = datetime.now()
|
||||
if log_enabled(BASIC):
|
||||
log(BASIC, 'stop collecting usage metrics')
|
||||
|
||||
@property
|
||||
def elapsed_time(self):
|
||||
if self.connection_stop_time:
|
||||
return self.connection_stop_time - self.open_socket_start_time
|
||||
else:
|
||||
return (datetime.now() - self.open_socket_start_time) if self.open_socket_start_time else timedelta(0)
|
|
@ -0,0 +1,334 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.04.28
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 os import linesep
|
||||
|
||||
from .. import SUBTREE, DEREF_ALWAYS, ALL_ATTRIBUTES, DEREF_NEVER
|
||||
from .microsoft.dirSync import DirSync
|
||||
from .microsoft.modifyPassword import ad_modify_password
|
||||
from .microsoft.unlockAccount import ad_unlock_account
|
||||
from .microsoft.addMembersToGroups import ad_add_members_to_groups
|
||||
from .microsoft.removeMembersFromGroups import ad_remove_members_from_groups
|
||||
from .microsoft.persistentSearch import ADPersistentSearch
|
||||
from .novell.partition_entry_count import PartitionEntryCount
|
||||
from .novell.replicaInfo import ReplicaInfo
|
||||
from .novell.listReplicas import ListReplicas
|
||||
from .novell.getBindDn import GetBindDn
|
||||
from .novell.nmasGetUniversalPassword import NmasGetUniversalPassword
|
||||
from .novell.nmasSetUniversalPassword import NmasSetUniversalPassword
|
||||
from .novell.startTransaction import StartTransaction
|
||||
from .novell.endTransaction import EndTransaction
|
||||
from .novell.addMembersToGroups import edir_add_members_to_groups
|
||||
from .novell.removeMembersFromGroups import edir_remove_members_from_groups
|
||||
from .novell.checkGroupsMemberships import edir_check_groups_memberships
|
||||
from .standard.whoAmI import WhoAmI
|
||||
from .standard.modifyPassword import ModifyPassword
|
||||
from .standard.PagedSearch import paged_search_generator, paged_search_accumulator
|
||||
from .standard.PersistentSearch import PersistentSearch
|
||||
|
||||
|
||||
class ExtendedOperationContainer(object):
|
||||
def __init__(self, connection):
|
||||
self._connection = connection
|
||||
|
||||
def __repr__(self):
|
||||
return linesep.join([' ' + element for element in dir(self) if element[0] != '_'])
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
|
||||
class StandardExtendedOperations(ExtendedOperationContainer):
|
||||
def who_am_i(self, controls=None):
|
||||
return WhoAmI(self._connection,
|
||||
controls).send()
|
||||
|
||||
def modify_password(self,
|
||||
user=None,
|
||||
old_password=None,
|
||||
new_password=None,
|
||||
hash_algorithm=None,
|
||||
salt=None,
|
||||
controls=None):
|
||||
|
||||
return ModifyPassword(self._connection,
|
||||
user,
|
||||
old_password,
|
||||
new_password,
|
||||
hash_algorithm,
|
||||
salt,
|
||||
controls).send()
|
||||
|
||||
def paged_search(self,
|
||||
search_base,
|
||||
search_filter,
|
||||
search_scope=SUBTREE,
|
||||
dereference_aliases=DEREF_ALWAYS,
|
||||
attributes=None,
|
||||
size_limit=0,
|
||||
time_limit=0,
|
||||
types_only=False,
|
||||
get_operational_attributes=False,
|
||||
controls=None,
|
||||
paged_size=100,
|
||||
paged_criticality=False,
|
||||
generator=True):
|
||||
|
||||
if generator:
|
||||
return paged_search_generator(self._connection,
|
||||
search_base,
|
||||
search_filter,
|
||||
search_scope,
|
||||
dereference_aliases,
|
||||
attributes,
|
||||
size_limit,
|
||||
time_limit,
|
||||
types_only,
|
||||
get_operational_attributes,
|
||||
controls,
|
||||
paged_size,
|
||||
paged_criticality)
|
||||
else:
|
||||
return paged_search_accumulator(self._connection,
|
||||
search_base,
|
||||
search_filter,
|
||||
search_scope,
|
||||
dereference_aliases,
|
||||
attributes,
|
||||
size_limit,
|
||||
time_limit,
|
||||
types_only,
|
||||
get_operational_attributes,
|
||||
controls,
|
||||
paged_size,
|
||||
paged_criticality)
|
||||
|
||||
def persistent_search(self,
|
||||
search_base='',
|
||||
search_filter='(objectclass=*)',
|
||||
search_scope=SUBTREE,
|
||||
dereference_aliases=DEREF_NEVER,
|
||||
attributes=ALL_ATTRIBUTES,
|
||||
size_limit=0,
|
||||
time_limit=0,
|
||||
controls=None,
|
||||
changes_only=True,
|
||||
show_additions=True,
|
||||
show_deletions=True,
|
||||
show_modifications=True,
|
||||
show_dn_modifications=True,
|
||||
notifications=True,
|
||||
streaming=True,
|
||||
callback=None
|
||||
):
|
||||
events_type = 0
|
||||
if show_additions:
|
||||
events_type += 1
|
||||
if show_deletions:
|
||||
events_type += 2
|
||||
if show_modifications:
|
||||
events_type += 4
|
||||
if show_dn_modifications:
|
||||
events_type += 8
|
||||
|
||||
if callback:
|
||||
streaming = False
|
||||
return PersistentSearch(self._connection,
|
||||
search_base,
|
||||
search_filter,
|
||||
search_scope,
|
||||
dereference_aliases,
|
||||
attributes,
|
||||
size_limit,
|
||||
time_limit,
|
||||
controls,
|
||||
changes_only,
|
||||
events_type,
|
||||
notifications,
|
||||
streaming,
|
||||
callback)
|
||||
|
||||
def funnel_search(self,
|
||||
search_base='',
|
||||
search_filter='',
|
||||
search_scope=SUBTREE,
|
||||
dereference_aliases=DEREF_NEVER,
|
||||
attributes=ALL_ATTRIBUTES,
|
||||
size_limit=0,
|
||||
time_limit=0,
|
||||
controls=None,
|
||||
streaming=False,
|
||||
callback=None
|
||||
):
|
||||
return PersistentSearch(self._connection,
|
||||
search_base,
|
||||
search_filter,
|
||||
search_scope,
|
||||
dereference_aliases,
|
||||
attributes,
|
||||
size_limit,
|
||||
time_limit,
|
||||
controls,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
streaming,
|
||||
callback)
|
||||
|
||||
|
||||
class NovellExtendedOperations(ExtendedOperationContainer):
|
||||
def get_bind_dn(self, controls=None):
|
||||
return GetBindDn(self._connection,
|
||||
controls).send()
|
||||
|
||||
def get_universal_password(self, user, controls=None):
|
||||
return NmasGetUniversalPassword(self._connection,
|
||||
user,
|
||||
controls).send()
|
||||
|
||||
def set_universal_password(self, user, new_password=None, controls=None):
|
||||
return NmasSetUniversalPassword(self._connection,
|
||||
user,
|
||||
new_password,
|
||||
controls).send()
|
||||
|
||||
def list_replicas(self, server_dn, controls=None):
|
||||
return ListReplicas(self._connection,
|
||||
server_dn,
|
||||
controls).send()
|
||||
|
||||
def partition_entry_count(self, partition_dn, controls=None):
|
||||
return PartitionEntryCount(self._connection,
|
||||
partition_dn,
|
||||
controls).send()
|
||||
|
||||
def replica_info(self, server_dn, partition_dn, controls=None):
|
||||
return ReplicaInfo(self._connection,
|
||||
server_dn,
|
||||
partition_dn,
|
||||
controls).send()
|
||||
|
||||
def start_transaction(self, controls=None):
|
||||
return StartTransaction(self._connection,
|
||||
controls).send()
|
||||
|
||||
def end_transaction(self, commit=True, controls=None): # attach the groupingControl to commit, None to abort transaction
|
||||
return EndTransaction(self._connection,
|
||||
commit,
|
||||
controls).send()
|
||||
|
||||
def add_members_to_groups(self, members, groups, fix=True, transaction=True):
|
||||
return edir_add_members_to_groups(self._connection,
|
||||
members_dn=members,
|
||||
groups_dn=groups,
|
||||
fix=fix,
|
||||
transaction=transaction)
|
||||
|
||||
def remove_members_from_groups(self, members, groups, fix=True, transaction=True):
|
||||
return edir_remove_members_from_groups(self._connection,
|
||||
members_dn=members,
|
||||
groups_dn=groups,
|
||||
fix=fix,
|
||||
transaction=transaction)
|
||||
|
||||
def check_groups_memberships(self, members, groups, fix=False, transaction=True):
|
||||
return edir_check_groups_memberships(self._connection,
|
||||
members_dn=members,
|
||||
groups_dn=groups,
|
||||
fix=fix,
|
||||
transaction=transaction)
|
||||
|
||||
|
||||
class MicrosoftExtendedOperations(ExtendedOperationContainer):
|
||||
def dir_sync(self,
|
||||
sync_base,
|
||||
sync_filter='(objectclass=*)',
|
||||
attributes=ALL_ATTRIBUTES,
|
||||
cookie=None,
|
||||
object_security=False,
|
||||
ancestors_first=True,
|
||||
public_data_only=False,
|
||||
incremental_values=True,
|
||||
max_length=2147483647,
|
||||
hex_guid=False):
|
||||
return DirSync(self._connection,
|
||||
sync_base=sync_base,
|
||||
sync_filter=sync_filter,
|
||||
attributes=attributes,
|
||||
cookie=cookie,
|
||||
object_security=object_security,
|
||||
ancestors_first=ancestors_first,
|
||||
public_data_only=public_data_only,
|
||||
incremental_values=incremental_values,
|
||||
max_length=max_length,
|
||||
hex_guid=hex_guid)
|
||||
|
||||
def modify_password(self, user, new_password, old_password=None, controls=None):
|
||||
return ad_modify_password(self._connection,
|
||||
user,
|
||||
new_password,
|
||||
old_password,
|
||||
controls)
|
||||
|
||||
def unlock_account(self, user):
|
||||
return ad_unlock_account(self._connection,
|
||||
user)
|
||||
|
||||
def add_members_to_groups(self, members, groups, fix=True):
|
||||
return ad_add_members_to_groups(self._connection,
|
||||
members_dn=members,
|
||||
groups_dn=groups,
|
||||
fix=fix)
|
||||
|
||||
def remove_members_from_groups(self, members, groups, fix=True):
|
||||
return ad_remove_members_from_groups(self._connection,
|
||||
members_dn=members,
|
||||
groups_dn=groups,
|
||||
fix=fix)
|
||||
|
||||
def persistent_search(self,
|
||||
search_base='',
|
||||
search_scope=SUBTREE,
|
||||
attributes=ALL_ATTRIBUTES,
|
||||
streaming=True,
|
||||
callback=None
|
||||
):
|
||||
|
||||
if callback:
|
||||
streaming = False
|
||||
return ADPersistentSearch(self._connection,
|
||||
search_base,
|
||||
search_scope,
|
||||
attributes,
|
||||
streaming,
|
||||
callback)
|
||||
|
||||
|
||||
class ExtendedOperationsRoot(ExtendedOperationContainer):
|
||||
def __init__(self, connection):
|
||||
ExtendedOperationContainer.__init__(self, connection) # calls super
|
||||
self.standard = StandardExtendedOperations(self._connection)
|
||||
self.novell = NovellExtendedOperations(self._connection)
|
||||
self.microsoft = MicrosoftExtendedOperations(self._connection)
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,98 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.12.26
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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 SEQUENCE_TYPES, MODIFY_ADD, BASE, DEREF_NEVER
|
||||
from ...core.exceptions import LDAPInvalidDnError, LDAPOperationsErrorResult
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
def ad_add_members_to_groups(connection,
|
||||
members_dn,
|
||||
groups_dn,
|
||||
fix=True,
|
||||
raise_error=False):
|
||||
"""
|
||||
:param connection: a bound Connection object
|
||||
:param members_dn: the list of members to add to groups
|
||||
:param groups_dn: the list of groups where members are to be added
|
||||
:param fix: checks for group existence and already assigned members
|
||||
:param raise_error: If the operation fails it raises an error instead of returning False
|
||||
:return: a boolean where True means that the operation was successful and False means an error has happened
|
||||
Establishes users-groups relations following the Active Directory rules: users are added to the member attribute of groups.
|
||||
Raises LDAPInvalidDnError if members or groups are not found in the DIT.
|
||||
"""
|
||||
|
||||
if not isinstance(members_dn, SEQUENCE_TYPES):
|
||||
members_dn = [members_dn]
|
||||
|
||||
if not isinstance(groups_dn, SEQUENCE_TYPES):
|
||||
groups_dn = [groups_dn]
|
||||
|
||||
if connection.check_names: # builds new lists with sanitized dn
|
||||
members_dn = [safe_dn(member_dn) for member_dn in members_dn]
|
||||
groups_dn = [safe_dn(group_dn) for group_dn in groups_dn]
|
||||
|
||||
error = False
|
||||
for group in groups_dn:
|
||||
if fix: # checks for existance of group and for already assigned members
|
||||
result = connection.search(group, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['member'])
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
response = connection.response
|
||||
result = connection.result
|
||||
|
||||
if not result['description'] == 'success':
|
||||
raise LDAPInvalidDnError(group + ' not found')
|
||||
|
||||
existing_members = response[0]['attributes']['member'] if 'member' in response[0]['attributes'] else []
|
||||
existing_members = [element.lower() for element in existing_members]
|
||||
else:
|
||||
existing_members = []
|
||||
|
||||
changes = dict()
|
||||
member_to_add = [element for element in members_dn if element.lower() not in existing_members]
|
||||
if member_to_add:
|
||||
changes['member'] = (MODIFY_ADD, member_to_add)
|
||||
if changes:
|
||||
result = connection.modify(group, changes)
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
result_error_params = ['result', 'description', 'dn', 'message']
|
||||
if raise_error:
|
||||
raise LDAPOperationsErrorResult([(k, v) for k, v in result.items() if k in result_error_params])
|
||||
break
|
||||
|
||||
return not error # returns True if no error is raised in the LDAP operations
|
|
@ -0,0 +1,94 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2015.10.21
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2015 - 2020 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 ...core.exceptions import LDAPExtensionError
|
||||
from ...protocol.microsoft import dir_sync_control, extended_dn_control, show_deleted_control
|
||||
from ... import SUBTREE, DEREF_NEVER
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
class DirSync(object):
|
||||
def __init__(self,
|
||||
connection,
|
||||
sync_base,
|
||||
sync_filter,
|
||||
attributes,
|
||||
cookie,
|
||||
object_security,
|
||||
ancestors_first,
|
||||
public_data_only,
|
||||
incremental_values,
|
||||
max_length,
|
||||
hex_guid
|
||||
):
|
||||
self.connection = connection
|
||||
if self.connection.check_names and sync_base:
|
||||
self. base = safe_dn(sync_base)
|
||||
else:
|
||||
self.base = sync_base
|
||||
self.filter = sync_filter
|
||||
self.attributes = attributes
|
||||
self.cookie = cookie
|
||||
self.object_security = object_security
|
||||
self.ancestors_first = ancestors_first
|
||||
self.public_data_only = public_data_only
|
||||
self.incremental_values = incremental_values
|
||||
self.max_length = max_length
|
||||
self.hex_guid = hex_guid
|
||||
self.more_results = True
|
||||
|
||||
def loop(self):
|
||||
result = self.connection.search(search_base=self.base,
|
||||
search_filter=self.filter,
|
||||
search_scope=SUBTREE,
|
||||
attributes=self.attributes,
|
||||
dereference_aliases=DEREF_NEVER,
|
||||
controls=[dir_sync_control(criticality=True,
|
||||
object_security=self.object_security,
|
||||
ancestors_first=self.ancestors_first,
|
||||
public_data_only=self.public_data_only,
|
||||
incremental_values=self.incremental_values,
|
||||
max_length=self.max_length, cookie=self.cookie),
|
||||
extended_dn_control(criticality=False, hex_format=self.hex_guid),
|
||||
show_deleted_control(criticality=False)]
|
||||
)
|
||||
if not self.connection.strategy.sync:
|
||||
response, result = self.connection.get_response(result)
|
||||
else:
|
||||
if self.connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
response = self.connection.response
|
||||
result = self.connection.result
|
||||
|
||||
if result['description'] == 'success' and 'controls' in result and '1.2.840.113556.1.4.841' in result['controls']:
|
||||
self.more_results = result['controls']['1.2.840.113556.1.4.841']['value']['more_results']
|
||||
self.cookie = result['controls']['1.2.840.113556.1.4.841']['value']['cookie']
|
||||
return response
|
||||
elif 'controls' in result:
|
||||
raise LDAPExtensionError('Missing DirSync control in response from server')
|
||||
else:
|
||||
raise LDAPExtensionError('error %r in DirSync' % result)
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2015.11.27
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2015 - 2020 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 MODIFY_REPLACE, MODIFY_DELETE, MODIFY_ADD
|
||||
from ...utils.log import log, log_enabled, PROTOCOL
|
||||
from ...core.results import RESULT_SUCCESS
|
||||
from ...utils.dn import safe_dn
|
||||
from ...utils.conv import to_unicode
|
||||
|
||||
|
||||
def ad_modify_password(connection, user_dn, new_password, old_password, controls=None):
|
||||
# old password must be None to reset password with sufficient privileges
|
||||
if connection.check_names:
|
||||
user_dn = safe_dn(user_dn)
|
||||
if str is bytes: # python2, converts to unicode
|
||||
new_password = to_unicode(new_password)
|
||||
if old_password:
|
||||
old_password = to_unicode(old_password)
|
||||
|
||||
encoded_new_password = ('"%s"' % new_password).encode('utf-16-le')
|
||||
|
||||
if old_password: # normal users must specify old and new password
|
||||
encoded_old_password = ('"%s"' % old_password).encode('utf-16-le')
|
||||
result = connection.modify(user_dn,
|
||||
{'unicodePwd': [(MODIFY_DELETE, [encoded_old_password]),
|
||||
(MODIFY_ADD, [encoded_new_password])]},
|
||||
controls)
|
||||
else: # admin users can reset password without sending the old one
|
||||
result = connection.modify(user_dn,
|
||||
{'unicodePwd': [(MODIFY_REPLACE, [encoded_new_password])]},
|
||||
controls)
|
||||
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
|
||||
# change successful, returns True
|
||||
if result['result'] == RESULT_SUCCESS:
|
||||
return True
|
||||
|
||||
# change was not successful, raises exception if raise_exception = True in connection or returns the operation result, error code is in result['result']
|
||||
if connection.raise_exceptions:
|
||||
from ...core.exceptions import LDAPOperationResult
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'operation result <%s> for <%s>', result, connection)
|
||||
raise LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'], response_type=result['type'])
|
||||
|
||||
return False
|
|
@ -0,0 +1,117 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.07.08
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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/>.
|
||||
|
||||
try:
|
||||
from queue import Empty
|
||||
except ImportError: # Python 2
|
||||
# noinspection PyUnresolvedReferences
|
||||
from Queue import Empty
|
||||
|
||||
from ...core.exceptions import LDAPExtensionError
|
||||
from ...utils.dn import safe_dn
|
||||
from ...protocol.microsoft import persistent_search_control
|
||||
|
||||
|
||||
class ADPersistentSearch(object):
|
||||
def __init__(self,
|
||||
connection,
|
||||
search_base,
|
||||
search_scope,
|
||||
attributes,
|
||||
streaming,
|
||||
callback
|
||||
):
|
||||
if connection.strategy.sync:
|
||||
raise LDAPExtensionError('Persistent Search needs an asynchronous streaming connection')
|
||||
|
||||
if connection.check_names and search_base:
|
||||
search_base = safe_dn(search_base)
|
||||
|
||||
self.connection = connection
|
||||
self.message_id = None
|
||||
self.base = search_base
|
||||
self.scope = search_scope
|
||||
self.attributes = attributes
|
||||
self.controls = [persistent_search_control()]
|
||||
|
||||
# this is the only filter permitted by AD persistent search
|
||||
self.filter = '(objectClass=*)'
|
||||
|
||||
self.connection.strategy.streaming = streaming
|
||||
if callback and callable(callback):
|
||||
self.connection.strategy.callback = callback
|
||||
elif callback:
|
||||
raise LDAPExtensionError('callback is not callable')
|
||||
|
||||
self.start()
|
||||
|
||||
def start(self):
|
||||
if self.message_id: # persistent search already started
|
||||
return
|
||||
|
||||
if not self.connection.bound:
|
||||
self.connection.bind()
|
||||
|
||||
with self.connection.strategy.async_lock:
|
||||
self.message_id = self.connection.search(search_base=self.base,
|
||||
search_filter=self.filter,
|
||||
search_scope=self.scope,
|
||||
attributes=self.attributes,
|
||||
controls=self.controls)
|
||||
self.connection.strategy.persistent_search_message_id = self.message_id
|
||||
|
||||
def stop(self, unbind=True):
|
||||
self.connection.abandon(self.message_id)
|
||||
if unbind:
|
||||
self.connection.unbind()
|
||||
if self.message_id in self.connection.strategy._responses:
|
||||
del self.connection.strategy._responses[self.message_id]
|
||||
if hasattr(self.connection.strategy, '_requests') and self.message_id in self.connection.strategy._requests: # asynchronous strategy has a dict of request that could be returned by get_response()
|
||||
del self.connection.strategy._requests[self.message_id]
|
||||
self.connection.strategy.persistent_search_message_id = None
|
||||
self.message_id = None
|
||||
|
||||
def next(self, block=False, timeout=None):
|
||||
if not self.connection.strategy.streaming and not self.connection.strategy.callback:
|
||||
try:
|
||||
return self.connection.strategy.events.get(block, timeout)
|
||||
except Empty:
|
||||
return None
|
||||
|
||||
raise LDAPExtensionError('Persistent search is not accumulating events in queue')
|
||||
|
||||
def funnel(self, block=False, timeout=None):
|
||||
done = False
|
||||
while not done:
|
||||
try:
|
||||
entry = self.connection.strategy.events.get(block, timeout)
|
||||
except Empty:
|
||||
yield None
|
||||
if entry['type'] == 'searchResEntry':
|
||||
yield entry
|
||||
else:
|
||||
done = True
|
||||
|
||||
yield entry
|
|
@ -0,0 +1,99 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.12.26
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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 ...core.exceptions import LDAPInvalidDnError, LDAPOperationsErrorResult
|
||||
from ... import SEQUENCE_TYPES, MODIFY_DELETE, BASE, DEREF_NEVER
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
def ad_remove_members_from_groups(connection,
|
||||
members_dn,
|
||||
groups_dn,
|
||||
fix,
|
||||
raise_error=False):
|
||||
"""
|
||||
:param connection: a bound Connection object
|
||||
:param members_dn: the list of members to remove from groups
|
||||
:param groups_dn: the list of groups where members are to be removed
|
||||
:param fix: checks for group existence and existing members
|
||||
:param raise_error: If the operation fails it raises an error instead of returning False
|
||||
:return: a boolean where True means that the operation was successful and False means an error has happened
|
||||
Removes users-groups relations following the Activwe Directory rules: users are removed from groups' member attribute
|
||||
|
||||
"""
|
||||
if not isinstance(members_dn, SEQUENCE_TYPES):
|
||||
members_dn = [members_dn]
|
||||
|
||||
if not isinstance(groups_dn, SEQUENCE_TYPES):
|
||||
groups_dn = [groups_dn]
|
||||
|
||||
if connection.check_names: # builds new lists with sanitized dn
|
||||
members_dn = [safe_dn(member_dn) for member_dn in members_dn]
|
||||
groups_dn = [safe_dn(group_dn) for group_dn in groups_dn]
|
||||
|
||||
error = False
|
||||
|
||||
for group in groups_dn:
|
||||
if fix: # checks for existance of group and for already assigned members
|
||||
result = connection.search(group, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['member'])
|
||||
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
response = connection.response
|
||||
result = connection.result
|
||||
|
||||
if not result['description'] == 'success':
|
||||
raise LDAPInvalidDnError(group + ' not found')
|
||||
|
||||
existing_members = response[0]['attributes']['member'] if 'member' in response[0]['attributes'] else []
|
||||
else:
|
||||
existing_members = members_dn
|
||||
|
||||
existing_members = [element.lower() for element in existing_members]
|
||||
changes = dict()
|
||||
member_to_remove = [element for element in members_dn if element.lower() in existing_members]
|
||||
if member_to_remove:
|
||||
changes['member'] = (MODIFY_DELETE, member_to_remove)
|
||||
if changes:
|
||||
result = connection.modify(group, changes)
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
result_error_params = ['result', 'description', 'dn', 'message']
|
||||
if raise_error:
|
||||
raise LDAPOperationsErrorResult([(k, v) for k, v in result.items() if k in result_error_params])
|
||||
break
|
||||
|
||||
return not error
|
|
@ -0,0 +1,57 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.11.01
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2015 - 2020 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 MODIFY_REPLACE
|
||||
from ...utils.log import log, log_enabled, PROTOCOL
|
||||
from ...core.results import RESULT_SUCCESS
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
def ad_unlock_account(connection, user_dn, controls=None):
|
||||
if connection.check_names:
|
||||
user_dn = safe_dn(user_dn)
|
||||
result = connection.modify(user_dn, {'lockoutTime': [(MODIFY_REPLACE, ['0'])]}, controls)
|
||||
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
|
||||
# change successful, returns True
|
||||
if result['result'] == RESULT_SUCCESS:
|
||||
return True
|
||||
|
||||
# change was not successful, raises exception if raise_exception = True in connection or returns the operation result, error code is in result['result']
|
||||
if connection.raise_exceptions:
|
||||
from ...core.exceptions import LDAPOperationResult
|
||||
if log_enabled(PROTOCOL):
|
||||
log(PROTOCOL, 'operation result <%s> for <%s>', result, connection)
|
||||
raise LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'], response_type=result['type'])
|
||||
|
||||
return result
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,167 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.04.16
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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 ...core.exceptions import LDAPInvalidDnError
|
||||
from ... import SEQUENCE_TYPES, MODIFY_ADD, BASE, DEREF_NEVER
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
def edir_add_members_to_groups(connection,
|
||||
members_dn,
|
||||
groups_dn,
|
||||
fix,
|
||||
transaction):
|
||||
"""
|
||||
:param connection: a bound Connection object
|
||||
:param members_dn: the list of members to add to groups
|
||||
:param groups_dn: the list of groups where members are to be added
|
||||
:param fix: checks for inconsistences in the users-groups relation and fixes them
|
||||
:param transaction: activates an LDAP transaction
|
||||
:return: a boolean where True means that the operation was successful and False means an error has happened
|
||||
Establishes users-groups relations following the eDirectory rules: groups are added to securityEquals and groupMembership
|
||||
attributes in the member object while members are added to member and equivalentToMe attributes in the group object.
|
||||
Raises LDAPInvalidDnError if members or groups are not found in the DIT.
|
||||
"""
|
||||
if not isinstance(members_dn, SEQUENCE_TYPES):
|
||||
members_dn = [members_dn]
|
||||
|
||||
if not isinstance(groups_dn, SEQUENCE_TYPES):
|
||||
groups_dn = [groups_dn]
|
||||
|
||||
transaction_control = None
|
||||
error = False
|
||||
|
||||
if connection.check_names: # builds new lists with sanitized dn
|
||||
safe_members_dn = []
|
||||
safe_groups_dn = []
|
||||
for member_dn in members_dn:
|
||||
safe_members_dn.append(safe_dn(member_dn))
|
||||
for group_dn in groups_dn:
|
||||
safe_groups_dn.append(safe_dn(group_dn))
|
||||
|
||||
members_dn = safe_members_dn
|
||||
groups_dn = safe_groups_dn
|
||||
|
||||
if transaction:
|
||||
transaction_control = connection.extend.novell.start_transaction()
|
||||
|
||||
if not error:
|
||||
for member in members_dn:
|
||||
if fix: # checks for existance of member and for already assigned groups
|
||||
result = connection.search(member, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['securityEquals', 'groupMembership'])
|
||||
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
response = connection.response
|
||||
|
||||
if not result['description'] == 'success':
|
||||
raise LDAPInvalidDnError(member + ' not found')
|
||||
|
||||
existing_security_equals = response[0]['attributes']['securityEquals'] if 'securityEquals' in response[0]['attributes'] else []
|
||||
existing_group_membership = response[0]['attributes']['groupMembership'] if 'groupMembership' in response[0]['attributes'] else []
|
||||
existing_security_equals = [element.lower() for element in existing_security_equals]
|
||||
existing_group_membership = [element.lower() for element in existing_group_membership]
|
||||
else:
|
||||
existing_security_equals = []
|
||||
existing_group_membership = []
|
||||
changes = dict()
|
||||
security_equals_to_add = [element for element in groups_dn if element.lower() not in existing_security_equals]
|
||||
group_membership_to_add = [element for element in groups_dn if element.lower() not in existing_group_membership]
|
||||
if security_equals_to_add:
|
||||
changes['securityEquals'] = (MODIFY_ADD, security_equals_to_add)
|
||||
if group_membership_to_add:
|
||||
changes['groupMembership'] = (MODIFY_ADD, group_membership_to_add)
|
||||
if changes:
|
||||
result = connection.modify(member, changes, controls=[transaction_control] if transaction else None)
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
break
|
||||
|
||||
if not error:
|
||||
for group in groups_dn:
|
||||
if fix: # checks for existance of group and for already assigned members
|
||||
result = connection.search(group, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['member', 'equivalentToMe'])
|
||||
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
response = connection.response
|
||||
|
||||
if not result['description'] == 'success':
|
||||
raise LDAPInvalidDnError(group + ' not found')
|
||||
|
||||
existing_members = response[0]['attributes']['member'] if 'member' in response[0]['attributes'] else []
|
||||
existing_equivalent_to_me = response[0]['attributes']['equivalentToMe'] if 'equivalentToMe' in response[0]['attributes'] else []
|
||||
existing_members = [element.lower() for element in existing_members]
|
||||
existing_equivalent_to_me = [element.lower() for element in existing_equivalent_to_me]
|
||||
else:
|
||||
existing_members = []
|
||||
existing_equivalent_to_me = []
|
||||
|
||||
changes = dict()
|
||||
member_to_add = [element for element in members_dn if element.lower() not in existing_members]
|
||||
equivalent_to_me_to_add = [element for element in members_dn if element.lower() not in existing_equivalent_to_me]
|
||||
if member_to_add:
|
||||
changes['member'] = (MODIFY_ADD, member_to_add)
|
||||
if equivalent_to_me_to_add:
|
||||
changes['equivalentToMe'] = (MODIFY_ADD, equivalent_to_me_to_add)
|
||||
if changes:
|
||||
result = connection.modify(group, changes, controls=[transaction_control] if transaction else None)
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
break
|
||||
|
||||
if transaction:
|
||||
if error: # aborts transaction in case of error in the modify operations
|
||||
result = connection.extend.novell.end_transaction(commit=False, controls=[transaction_control])
|
||||
else:
|
||||
result = connection.extend.novell.end_transaction(commit=True, controls=[transaction_control])
|
||||
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
|
||||
return not error # returns True if no error is raised in the LDAP operations
|
|
@ -0,0 +1,180 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.05.14
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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 .addMembersToGroups import edir_add_members_to_groups
|
||||
from ...core.exceptions import LDAPInvalidDnError
|
||||
from ... import SEQUENCE_TYPES, BASE, DEREF_NEVER
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
def _check_members_have_memberships(connection,
|
||||
members_dn,
|
||||
groups_dn):
|
||||
"""
|
||||
:param connection: a bound Connection object
|
||||
:param members_dn: the list of members to add to groups
|
||||
:param groups_dn: the list of groups where members are to be added
|
||||
:return: two booleans. The first when True means that all members have membership in all groups, The second when True means that
|
||||
there are inconsistences in the securityEquals attribute
|
||||
Checks user's group membership.
|
||||
Raises LDAPInvalidDNError if member is not found in the DIT.
|
||||
"""
|
||||
if not isinstance(members_dn, SEQUENCE_TYPES):
|
||||
members_dn = [members_dn]
|
||||
|
||||
if not isinstance(groups_dn, SEQUENCE_TYPES):
|
||||
groups_dn = [groups_dn]
|
||||
|
||||
partial = False # True when a member has groupMembership but doesn't have securityEquals
|
||||
for member in members_dn:
|
||||
result = connection.search(member, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['groupMembership', 'securityEquals'])
|
||||
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
response = connection.response
|
||||
|
||||
if not result['description'] == 'success': # member not found in DIT
|
||||
raise LDAPInvalidDnError(member + ' not found')
|
||||
|
||||
existing_security_equals = response[0]['attributes']['securityEquals'] if 'securityEquals' in response[0]['attributes'] else []
|
||||
existing_group_membership = response[0]['attributes']['groupMembership'] if 'groupMembership' in response[0]['attributes'] else []
|
||||
existing_security_equals = [element.lower() for element in existing_security_equals]
|
||||
existing_group_membership = [element.lower() for element in existing_group_membership]
|
||||
|
||||
for group in groups_dn:
|
||||
if group.lower() not in existing_group_membership:
|
||||
return False, False
|
||||
if group.lower() not in existing_security_equals:
|
||||
partial = True
|
||||
|
||||
return True, partial
|
||||
|
||||
|
||||
def _check_groups_contain_members(connection,
|
||||
groups_dn,
|
||||
members_dn):
|
||||
"""
|
||||
:param connection: a bound Connection object
|
||||
:param members_dn: the list of members to add to groups
|
||||
:param groups_dn: the list of groups where members are to be added
|
||||
:return: two booleans. The first when True means that all members have membership in all groups, The second when True means that
|
||||
there are inconsistences in the EquivalentToMe attribute
|
||||
Checks if groups have members in their 'member' attribute.
|
||||
Raises LDAPInvalidDNError if member is not found in the DIT.
|
||||
"""
|
||||
if not isinstance(groups_dn, SEQUENCE_TYPES):
|
||||
groups_dn = [groups_dn]
|
||||
|
||||
if not isinstance(members_dn, SEQUENCE_TYPES):
|
||||
members_dn = [members_dn]
|
||||
|
||||
partial = False # True when a group has member but doesn't have equivalentToMe
|
||||
for group in groups_dn:
|
||||
result = connection.search(group, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['member', 'equivalentToMe'])
|
||||
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
response = connection.response
|
||||
|
||||
if not result['description'] == 'success':
|
||||
raise LDAPInvalidDnError(group + ' not found')
|
||||
|
||||
existing_members = response[0]['attributes']['member'] if 'member' in response[0]['attributes'] else []
|
||||
existing_equivalent_to_me = response[0]['attributes']['equivalentToMe'] if 'equivalentToMe' in response[0]['attributes'] else []
|
||||
existing_members = [element.lower() for element in existing_members]
|
||||
existing_equivalent_to_me = [element.lower() for element in existing_equivalent_to_me]
|
||||
for member in members_dn:
|
||||
if member.lower() not in existing_members:
|
||||
return False, False
|
||||
if member.lower() not in existing_equivalent_to_me:
|
||||
partial = True
|
||||
|
||||
return True, partial
|
||||
|
||||
|
||||
def edir_check_groups_memberships(connection,
|
||||
members_dn,
|
||||
groups_dn,
|
||||
fix,
|
||||
transaction):
|
||||
"""
|
||||
:param connection: a bound Connection object
|
||||
:param members_dn: the list of members to check
|
||||
:param groups_dn: the list of groups to check
|
||||
:param fix: checks for inconsistences in the users-groups relation and fixes them
|
||||
:param transaction: activates an LDAP transaction when fixing
|
||||
:return: a boolean where True means that the operation was successful and False means an error has happened
|
||||
Checks and fixes users-groups relations following the eDirectory rules: groups are checked against 'groupMembership'
|
||||
attribute in the member object while members are checked against 'member' attribute in the group object.
|
||||
Raises LDAPInvalidDnError if members or groups are not found in the DIT.
|
||||
"""
|
||||
if not isinstance(groups_dn, SEQUENCE_TYPES):
|
||||
groups_dn = [groups_dn]
|
||||
|
||||
if not isinstance(members_dn, SEQUENCE_TYPES):
|
||||
members_dn = [members_dn]
|
||||
|
||||
if connection.check_names: # builds new lists with sanitized dn
|
||||
safe_members_dn = []
|
||||
safe_groups_dn = []
|
||||
for member_dn in members_dn:
|
||||
safe_members_dn.append(safe_dn(member_dn))
|
||||
for group_dn in groups_dn:
|
||||
safe_groups_dn.append(safe_dn(group_dn))
|
||||
|
||||
members_dn = safe_members_dn
|
||||
groups_dn = safe_groups_dn
|
||||
|
||||
try:
|
||||
members_have_memberships, partial_member_security = _check_members_have_memberships(connection, members_dn, groups_dn)
|
||||
groups_contain_members, partial_group_security = _check_groups_contain_members(connection, groups_dn, members_dn)
|
||||
except LDAPInvalidDnError:
|
||||
return False
|
||||
|
||||
if not members_have_memberships and not groups_contain_members:
|
||||
return False
|
||||
|
||||
if fix: # fix any inconsistences
|
||||
if (members_have_memberships and not groups_contain_members) \
|
||||
or (groups_contain_members and not members_have_memberships) \
|
||||
or partial_group_security \
|
||||
or partial_member_security:
|
||||
|
||||
for member in members_dn:
|
||||
for group in groups_dn:
|
||||
edir_add_members_to_groups(connection, member, group, True, transaction)
|
||||
|
||||
return True
|
|
@ -0,0 +1,58 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.04.14
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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 ...extend.operation import ExtendedOperation
|
||||
from ...protocol.novell import EndGroupTypeRequestValue, EndGroupTypeResponseValue, Sequence
|
||||
from ...utils.asn1 import decoder
|
||||
|
||||
|
||||
class EndTransaction(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.27.103.2'
|
||||
self.response_name = '2.16.840.1.113719.1.27.103.2'
|
||||
self.request_value = EndGroupTypeRequestValue()
|
||||
self.asn1_spec = EndGroupTypeResponseValue()
|
||||
|
||||
def __init__(self, connection, commit=True, controls=None):
|
||||
if controls and len(controls) == 1:
|
||||
group_cookie = decoder.decode(controls[0][2], asn1Spec=Sequence())[0][0] # get the cookie from the built groupingControl
|
||||
else:
|
||||
group_cookie = None
|
||||
controls = None
|
||||
|
||||
ExtendedOperation.__init__(self, connection, controls) # calls super __init__()
|
||||
if group_cookie:
|
||||
self.request_value['endGroupCookie'] = group_cookie # transactionGroupingType
|
||||
if not commit:
|
||||
self.request_value['endGroupValue'] = '' # an empty endGroupValue means abort transaction
|
||||
|
||||
def populate_result(self):
|
||||
try:
|
||||
self.result['value'] = self.decoded_response['endGroupValue']
|
||||
except TypeError:
|
||||
self.result['value'] = None
|
||||
|
||||
def set_response(self):
|
||||
self.response_value = self.result
|
|
@ -0,0 +1,41 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.04.30
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 ...protocol.novell import Identity
|
||||
from ...extend.operation import ExtendedOperation
|
||||
|
||||
|
||||
class GetBindDn(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.27.100.31'
|
||||
self.response_name = '2.16.840.1.113719.1.27.100.32'
|
||||
self.response_attribute = 'identity'
|
||||
self.asn1_spec = Identity()
|
||||
|
||||
def populate_result(self):
|
||||
try:
|
||||
self.result['identity'] = str(self.decoded_response) if self.decoded_response else None
|
||||
except TypeError:
|
||||
self.result['identity'] = None
|
|
@ -0,0 +1,50 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.07.03
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 ...extend.operation import ExtendedOperation
|
||||
from ...protocol.novell import ReplicaList
|
||||
from ...protocol.rfc4511 import LDAPDN
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
class ListReplicas(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.27.100.19'
|
||||
self.response_name = '2.16.840.1.113719.1.27.100.20'
|
||||
self.request_value = LDAPDN()
|
||||
self.asn1_spec = ReplicaList()
|
||||
self.response_attribute = 'replicas'
|
||||
|
||||
def __init__(self, connection, server_dn, controls=None):
|
||||
ExtendedOperation.__init__(self, connection, controls) # calls super __init__()
|
||||
if connection.check_names:
|
||||
server_dn = safe_dn(server_dn)
|
||||
self.request_value = LDAPDN(server_dn)
|
||||
|
||||
def populate_result(self):
|
||||
try:
|
||||
self.result['replicas'] = [str(replica) for replica in self.decoded_response] if self.decoded_response else None
|
||||
except TypeError:
|
||||
self.result['replicas'] = None
|
|
@ -0,0 +1,56 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.07.03
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 ...extend.operation import ExtendedOperation
|
||||
from ...protocol.novell import NmasGetUniversalPasswordRequestValue, NmasGetUniversalPasswordResponseValue, NMAS_LDAP_EXT_VERSION
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
class NmasGetUniversalPassword(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.39.42.100.13'
|
||||
self.response_name = '2.16.840.1.113719.1.39.42.100.14'
|
||||
self.request_value = NmasGetUniversalPasswordRequestValue()
|
||||
self.asn1_spec = NmasGetUniversalPasswordResponseValue()
|
||||
self.response_attribute = 'password'
|
||||
|
||||
def __init__(self, connection, user, controls=None):
|
||||
ExtendedOperation.__init__(self, connection, controls) # calls super __init__()
|
||||
|
||||
if connection.check_names:
|
||||
user = safe_dn(user)
|
||||
|
||||
self.request_value['nmasver'] = NMAS_LDAP_EXT_VERSION
|
||||
self.request_value['reqdn'] = user
|
||||
|
||||
def populate_result(self):
|
||||
if self.decoded_response:
|
||||
self.result['nmasver'] = int(self.decoded_response['nmasver'])
|
||||
self.result['error'] = int(self.decoded_response['err'])
|
||||
try:
|
||||
|
||||
self.result['password'] = str(self.decoded_response['passwd']) if self.decoded_response['passwd'].hasValue() else None
|
||||
except TypeError:
|
||||
self.result['password'] = None
|
|
@ -0,0 +1,52 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.07.03
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 ...extend.operation import ExtendedOperation
|
||||
from ...protocol.novell import NmasSetUniversalPasswordRequestValue, NmasSetUniversalPasswordResponseValue, NMAS_LDAP_EXT_VERSION
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
class NmasSetUniversalPassword(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.39.42.100.11'
|
||||
self.response_name = '2.16.840.1.113719.1.39.42.100.12'
|
||||
self.request_value = NmasSetUniversalPasswordRequestValue()
|
||||
self.asn1_spec = NmasSetUniversalPasswordResponseValue()
|
||||
self.response_attribute = 'password'
|
||||
|
||||
def __init__(self, connection, user, new_password, controls=None):
|
||||
ExtendedOperation.__init__(self, connection, controls) # calls super __init__()
|
||||
if connection.check_names and user:
|
||||
user = safe_dn(user)
|
||||
|
||||
self.request_value['nmasver'] = NMAS_LDAP_EXT_VERSION
|
||||
if user:
|
||||
self.request_value['reqdn'] = user
|
||||
if new_password:
|
||||
self.request_value['new_passwd'] = new_password
|
||||
|
||||
def populate_result(self):
|
||||
self.result['nmasver'] = int(self.decoded_response['nmasver'])
|
||||
self.result['error'] = int(self.decoded_response['err'])
|
|
@ -0,0 +1,57 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.08.05
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 pyasn1.type.univ import Integer
|
||||
|
||||
from ...core.exceptions import LDAPExtensionError
|
||||
from ..operation import ExtendedOperation
|
||||
from ...protocol.rfc4511 import LDAPDN
|
||||
from ...utils.asn1 import decoder
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
class PartitionEntryCount(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.27.100.13'
|
||||
self.response_name = '2.16.840.1.113719.1.27.100.14'
|
||||
self.request_value = LDAPDN()
|
||||
self.response_attribute = 'entry_count'
|
||||
|
||||
def __init__(self, connection, partition_dn, controls=None):
|
||||
ExtendedOperation.__init__(self, connection, controls) # calls super __init__()
|
||||
if connection.check_names:
|
||||
partition_dn = safe_dn(partition_dn)
|
||||
self.request_value = LDAPDN(partition_dn)
|
||||
|
||||
def populate_result(self):
|
||||
substrate = self.decoded_response
|
||||
try:
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['entry_count'] = int(decoded)
|
||||
except Exception:
|
||||
raise LDAPExtensionError('unable to decode substrate')
|
||||
|
||||
if substrate:
|
||||
raise LDAPExtensionError('unknown substrate remaining')
|
|
@ -0,0 +1,170 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.04.17
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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 ...core.exceptions import LDAPInvalidDnError
|
||||
from ... import SEQUENCE_TYPES, MODIFY_DELETE, BASE, DEREF_NEVER
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
def edir_remove_members_from_groups(connection,
|
||||
members_dn,
|
||||
groups_dn,
|
||||
fix,
|
||||
transaction):
|
||||
"""
|
||||
:param connection: a bound Connection object
|
||||
:param members_dn: the list of members to remove from groups
|
||||
:param groups_dn: the list of groups where members are to be removed
|
||||
:param fix: checks for inconsistences in the users-groups relation and fixes them
|
||||
:param transaction: activates an LDAP transaction
|
||||
:return: a boolean where True means that the operation was successful and False means an error has happened
|
||||
Removes users-groups relations following the eDirectory rules: groups are removed from securityEquals and groupMembership
|
||||
attributes in the member object while members are removed from member and equivalentToMe attributes in the group object.
|
||||
Raises LDAPInvalidDnError if members or groups are not found in the DIT.
|
||||
|
||||
"""
|
||||
if not isinstance(members_dn, SEQUENCE_TYPES):
|
||||
members_dn = [members_dn]
|
||||
|
||||
if not isinstance(groups_dn, SEQUENCE_TYPES):
|
||||
groups_dn = [groups_dn]
|
||||
|
||||
if connection.check_names: # builds new lists with sanitized dn
|
||||
safe_members_dn = []
|
||||
safe_groups_dn = []
|
||||
for member_dn in members_dn:
|
||||
safe_members_dn.append(safe_dn(member_dn))
|
||||
for group_dn in groups_dn:
|
||||
safe_groups_dn.append(safe_dn(group_dn))
|
||||
|
||||
members_dn = safe_members_dn
|
||||
groups_dn = safe_groups_dn
|
||||
|
||||
transaction_control = None
|
||||
error = False
|
||||
|
||||
if transaction:
|
||||
transaction_control = connection.extend.novell.start_transaction()
|
||||
|
||||
if not error:
|
||||
for member in members_dn:
|
||||
if fix: # checks for existance of member and for already assigned groups
|
||||
result = connection.search(member, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['securityEquals', 'groupMembership'])
|
||||
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
response = connection.response
|
||||
result = connection.result
|
||||
|
||||
if not result['description'] == 'success':
|
||||
raise LDAPInvalidDnError(member + ' not found')
|
||||
|
||||
existing_security_equals = response[0]['attributes']['securityEquals'] if 'securityEquals' in response[0]['attributes'] else []
|
||||
existing_group_membership = response[0]['attributes']['groupMembership'] if 'groupMembership' in response[0]['attributes'] else []
|
||||
else:
|
||||
existing_security_equals = groups_dn
|
||||
existing_group_membership = groups_dn
|
||||
existing_security_equals = [element.lower() for element in existing_security_equals]
|
||||
existing_group_membership = [element.lower() for element in existing_group_membership]
|
||||
|
||||
changes = dict()
|
||||
security_equals_to_remove = [element for element in groups_dn if element.lower() in existing_security_equals]
|
||||
group_membership_to_remove = [element for element in groups_dn if element.lower() in existing_group_membership]
|
||||
if security_equals_to_remove:
|
||||
changes['securityEquals'] = (MODIFY_DELETE, security_equals_to_remove)
|
||||
if group_membership_to_remove:
|
||||
changes['groupMembership'] = (MODIFY_DELETE, group_membership_to_remove)
|
||||
if changes:
|
||||
result = connection.modify(member, changes, controls=[transaction_control] if transaction else None)
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
break
|
||||
|
||||
if not error:
|
||||
for group in groups_dn:
|
||||
if fix: # checks for existance of group and for already assigned members
|
||||
result = connection.search(group, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['member', 'equivalentToMe'])
|
||||
|
||||
if not connection.strategy.sync:
|
||||
response, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, response, _ = result
|
||||
else:
|
||||
response = connection.response
|
||||
result = connection.result
|
||||
|
||||
if not result['description'] == 'success':
|
||||
raise LDAPInvalidDnError(group + ' not found')
|
||||
|
||||
existing_members = response[0]['attributes']['member'] if 'member' in response[0]['attributes'] else []
|
||||
existing_equivalent_to_me = response[0]['attributes']['equivalentToMe'] if 'equivalentToMe' in response[0]['attributes'] else []
|
||||
else:
|
||||
existing_members = members_dn
|
||||
existing_equivalent_to_me = members_dn
|
||||
|
||||
existing_members = [element.lower() for element in existing_members]
|
||||
existing_equivalent_to_me = [element.lower() for element in existing_equivalent_to_me]
|
||||
|
||||
changes = dict()
|
||||
member_to_remove = [element for element in members_dn if element.lower() in existing_members]
|
||||
equivalent_to_me_to_remove = [element for element in members_dn if element.lower() in existing_equivalent_to_me]
|
||||
if member_to_remove:
|
||||
changes['member'] = (MODIFY_DELETE, member_to_remove)
|
||||
if equivalent_to_me_to_remove:
|
||||
changes['equivalentToMe'] = (MODIFY_DELETE, equivalent_to_me_to_remove)
|
||||
if changes:
|
||||
result = connection.modify(group, changes, controls=[transaction_control] if transaction else None)
|
||||
if not connection.strategy.sync:
|
||||
_, result = connection.get_response(result)
|
||||
else:
|
||||
if connection.strategy.thread_safe:
|
||||
_, result, _, _ = result
|
||||
else:
|
||||
result = connection.result
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
break
|
||||
|
||||
if transaction:
|
||||
if error: # aborts transaction in case of error in the modify operations
|
||||
result = connection.extend.novell.end_transaction(commit=False, controls=[transaction_control])
|
||||
else:
|
||||
result = connection.extend.novell.end_transaction(commit=True, controls=[transaction_control])
|
||||
|
||||
if result['description'] != 'success':
|
||||
error = True
|
||||
|
||||
return not error # return True if no error is raised in the LDAP operations
|
|
@ -0,0 +1,79 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2014.08.07
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2014 - 2020 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 datetime import datetime
|
||||
|
||||
from pyasn1.type.univ import Integer
|
||||
|
||||
from ...core.exceptions import LDAPExtensionError
|
||||
from ...protocol.novell import LDAPDN, ReplicaInfoRequestValue
|
||||
from ..operation import ExtendedOperation
|
||||
from ...utils.asn1 import decoder
|
||||
from ...utils.dn import safe_dn
|
||||
|
||||
|
||||
class ReplicaInfo(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.27.100.17'
|
||||
self.response_name = '2.16.840.1.113719.1.27.100.18'
|
||||
# self.asn1_spec = ReplicaInfoResponseValue()
|
||||
self.request_value = ReplicaInfoRequestValue()
|
||||
self.response_attribute = 'partition_dn'
|
||||
|
||||
def __init__(self, connection, server_dn, partition_dn, controls=None):
|
||||
if connection.check_names:
|
||||
if server_dn:
|
||||
server_dn = safe_dn(server_dn)
|
||||
if partition_dn:
|
||||
partition_dn = safe_dn(partition_dn)
|
||||
|
||||
ExtendedOperation.__init__(self, connection, controls) # calls super __init__()
|
||||
self.request_value['server_dn'] = server_dn
|
||||
self.request_value['partition_dn'] = partition_dn
|
||||
|
||||
def populate_result(self):
|
||||
substrate = self.decoded_response
|
||||
try:
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['partition_id'] = int(decoded)
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['replica_state'] = int(decoded)
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['modification_time'] = datetime.utcfromtimestamp(int(decoded))
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['purge_time'] = datetime.utcfromtimestamp(int(decoded))
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['local_partition_id'] = int(decoded)
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=LDAPDN())
|
||||
self.result['partition_dn'] = str(decoded)
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['replica_type'] = int(decoded)
|
||||
decoded, substrate = decoder.decode(substrate, asn1Spec=Integer())
|
||||
self.result['flags'] = int(decoded)
|
||||
except Exception:
|
||||
raise LDAPExtensionError('unable to decode substrate')
|
||||
|
||||
if substrate:
|
||||
raise LDAPExtensionError('unknown substrate remaining')
|
|
@ -0,0 +1,56 @@
|
|||
"""
|
||||
"""
|
||||
|
||||
# Created on 2016.04.14
|
||||
#
|
||||
# Author: Giovanni Cannata
|
||||
#
|
||||
# Copyright 2016 - 2020 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 ...extend.operation import ExtendedOperation
|
||||
from ...protocol.novell import CreateGroupTypeRequestValue, CreateGroupTypeResponseValue, GroupingControlValue
|
||||
from ...protocol.controls import build_control
|
||||
|
||||
|
||||
class StartTransaction(ExtendedOperation):
|
||||
def config(self):
|
||||
self.request_name = '2.16.840.1.113719.1.27.103.1'
|
||||
self.response_name = '2.16.840.1.113719.1.27.103.1'
|
||||
self.request_value = CreateGroupTypeRequestValue()
|
||||
self.asn1_spec = CreateGroupTypeResponseValue()
|
||||
|
||||
def __init__(self, connection, controls=None):
|
||||
ExtendedOperation.__init__(self, connection, controls) # calls super __init__()
|
||||
self.request_value['createGroupType'] = '2.16.840.1.113719.1.27.103.7' # transactionGroupingType
|
||||
|
||||
def populate_result(self):
|
||||
self.result['cookie'] = int(self.decoded_response['createGroupCookie'])
|
||||
try:
|
||||
self.result['value'] = self.decoded_response['createGroupValue']
|
||||
except TypeError:
|
||||
self.result['value'] = None
|
||||
|
||||
def set_response(self):
|
||||
try:
|
||||
grouping_cookie_value = GroupingControlValue()
|
||||
grouping_cookie_value['groupingCookie'] = self.result['cookie']
|
||||
self.response_value = build_control('2.16.840.1.113719.1.27.103.7', True, grouping_cookie_value, encode_control_value=True) # groupingControl
|
||||
except TypeError:
|
||||
self.response_value = None
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue