diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/LICENSE.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2dbd8537045f8bd8396e9e0241588e635acdea4a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/LICENSE.txt
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013-2017 William Fagan
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..acb507e34431ce85157d5a37b7a3abe5bd7ab8b1
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/METADATA
@@ -0,0 +1,179 @@
+Metadata-Version: 2.1
+Name: Flask-Compress
+Version: 1.15
+Summary: Compress responses in your Flask app with gzip, deflate, brotli or zstandard.
+Home-page: https://github.com/colour-science/flask-compress
+Author: Thomas Mansencal
+Author-email: thomas.mansencal@gmail.com
+License: MIT
+Platform: any
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Description-Content-Type: text/markdown
+License-File: LICENSE.txt
+Requires-Dist: flask
+Requires-Dist: brotli ; platform_python_implementation != "PyPy"
+Requires-Dist: zstandard ; platform_python_implementation != "PyPy"
+Requires-Dist: brotlicffi ; platform_python_implementation == "PyPy"
+Requires-Dist: zstandard[cffi] ; platform_python_implementation == "PyPy"
+
+# Flask-Compress
+
+[](https://github.com/colour-science/flask-compress/actions/workflows/ci.yaml)
+[](https://pypi.python.org/pypi/Flask-Compress)
+[](https://pypi.python.org/pypi/Flask-Compress)
+
+Flask-Compress allows you to easily compress your [Flask](http://flask.pocoo.org/) application's responses with gzip, deflate or brotli. It originally started as a fork of [Flask-gzip](https://github.com/closeio/Flask-gzip).
+
+The preferred solution is to have a server (like [Nginx](http://wiki.nginx.org/Main)) automatically compress the static files for you. If you don't have that option Flask-Compress will solve the problem for you.
+
+
+## How it works
+
+Flask-Compress both adds the various headers required for a compressed response and compresses the response data.
+This makes serving compressed static files extremely easy.
+
+Internally, every time a request is made the extension will check if it matches one of the compressible MIME types
+and whether the client and the server use some common compression algorithm, and will automatically attach the
+appropriate headers.
+
+To determine the compression algorithm, the `Accept-Encoding` request header is inspected, respecting the
+quality factor as described in [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding).
+If no requested compression algorithm is supported by the server, we don't compress the response. If, on the other
+hand, multiple suitable algorithms are found and are requested with the same quality factor, we choose the first one
+defined in the `COMPRESS_ALGORITHM` option (see below).
+
+
+## Installation
+
+If you use pip then installation is simply:
+
+```shell
+$ pip install --user flask-compress
+```
+
+or, if you want the latest github version:
+
+```shell
+$ pip install --user git+git://github.com/colour-science/flask-compress.git
+```
+
+You can also install Flask-Compress via Easy Install:
+
+```shell
+$ easy_install flask-compress
+```
+
+
+## Using Flask-Compress
+
+### Globally
+
+Flask-Compress is incredibly simple to use. In order to start compressing your Flask application's assets, the first thing to do is let Flask-Compress know about your [`flask.Flask`](http://flask.pocoo.org/docs/latest/api/#flask.Flask) application object.
+
+```python
+from flask import Flask
+from flask_compress import Compress
+
+app = Flask(__name__)
+Compress(app)
+```
+
+In many cases, however, one cannot expect a Flask instance to be ready at import time, and a common pattern is to return a Flask instance from within a function only after other configuration details have been taken care of. In these cases, Flask-Compress provides a simple function, `flask_compress.Compress.init_app`, which takes your application as an argument.
+
+```python
+from flask import Flask
+from flask_compress import Compress
+
+compress = Compress()
+
+def start_app():
+ app = Flask(__name__)
+ compress.init_app(app)
+ return app
+```
+
+In terms of automatically compressing your assets, passing your [`flask.Flask`](http://flask.pocoo.org/docs/latest/api/#flask.Flask) object to the `flask_compress.Compress` object is all that needs to be done.
+
+### Per-view compression
+
+Compression is possible per view using the `@compress.compressed()` decorator. Make sure to disable global compression first.
+
+```python
+from flask import Flask
+from flask_compress import Compress
+
+app = Flask(__name__)
+app.config["COMPRESS_REGISTER"] = False # disable default compression of all eligible requests
+compress = Compress()
+compress.init_app(app)
+
+# Compress this view specifically
+@app.route("/test")
+@compress.compressed()
+def view():
+ pass
+```
+
+### Cache example
+
+Flask-Compress can be integrated with caching mechanisms to serve compressed responses directly from the cache. This can significantly reduce server load and response times.
+Here is an example of how to configure Flask-Compress with caching using Flask-Caching.
+The example demonstrates how to create a simple cache instance with a 1-hour timeout, and use it to cache compressed responses for incoming requests.
+
+```python
+# Initializing flask app
+app = Flask(__name__)
+
+cache = Cache(app, config={
+ 'CACHE_TYPE': 'simple',
+ 'CACHE_DEFAULT_TIMEOUT': 60*60 # 1 hour cache timeout
+})
+
+# Define a function to return cache key for incoming requests
+def get_cache_key(request):
+ return request.url
+
+# Initialize Flask-Compress
+compress = Compress()
+compress.init_app(app)
+
+# Set up cache for compressed responses
+compress.cache = cache
+compress.cache_key = get_cache_key
+```
+
+## Options
+
+Within your Flask application's settings you can provide the following settings to control the behavior of Flask-Compress. None of the settings are required.
+
+| Option | Description | Default |
+| ------ | ----------- | ------- |
+| `COMPRESS_MIMETYPES` | Set the list of mimetypes to compress here. | `[` `'application/javascript',` `'application/json',` `'text/css',` `'text/html',` `'text/javascript',` `'text/xml',` `]` |
+| `COMPRESS_LEVEL` | Specifies the gzip compression level. | `6` |
+| `COMPRESS_BR_LEVEL` | Specifies the Brotli compression level. Ranges from 0 to 11. | `4` |
+| `COMPRESS_BR_MODE` | For Brotli, the compression mode. The options are 0, 1, or 2. These correspond to "generic", "text" (for UTF-8 input), and "font" (for WOFF 2.0). | `0` |
+| `COMPRESS_BR_WINDOW` | For Brotli, this specifies the base-2 logarithm of the sliding window size. Ranges from 10 to 24. | `22` |
+| `COMPRESS_BR_BLOCK` | For Brotli, this provides the base-2 logarithm of the maximum input block size. If zero is provided, value will be determined based on the quality. Ranges from 16 to 24. | `0` |
+| `COMPRESS_ZSTD_LEVEL` | Specifies the ZStandard compression level. Ranges from 1 to 22. Levels >= 20, labeled ultra, should be used with caution, as they require more memory. 0 means use the default level. -131072 to -1, negative levels extend the range of speed vs ratio preferences. The lower the level, the faster the speed, but at the cost of compression ratio. | `3` |
+| `COMPRESS_DEFLATE_LEVEL` | Specifies the deflate compression level. | `-1` |
+| `COMPRESS_MIN_SIZE` | Specifies the minimum file size threshold for compressing files. | `500` |
+| `COMPRESS_CACHE_KEY` | Specifies the cache key method for lookup/storage of response data. | `None` |
+| `COMPRESS_CACHE_BACKEND` | Specified the backend for storing the cached response data. | `None` |
+| `COMPRESS_REGISTER` | Specifies if compression should be automatically registered. | `True` |
+| `COMPRESS_ALGORITHM` | Supported compression algorithms. | `['zstd', 'br', 'gzip', 'deflate']` |
+| `COMPRESS_STREAMS` | Compress content streams. | `True` |
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..3d22f3b6f8f7fa4aa94403f8f73cdc7202d41241
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/RECORD
@@ -0,0 +1,13 @@
+Flask_Compress-1.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_Compress-1.15.dist-info/LICENSE.txt,sha256=oZ51osarUWjhwPGF9tFLTwEwzZJlEbiPM4KDOiEeImk,1085
+Flask_Compress-1.15.dist-info/METADATA,sha256=KxuFhC8pghV6m0ibUZZApAvKNerelBI4ryRog1f46II,8371
+Flask_Compress-1.15.dist-info/RECORD,,
+Flask_Compress-1.15.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+Flask_Compress-1.15.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+Flask_Compress-1.15.dist-info/top_level.txt,sha256=R7cqncNaZ2mv8eO4-hZhJgv5Js4V9KHmiFsWPc3lG8w,15
+flask_compress/__init__.py,sha256=h2TT9zdxEuxudZk3-Ec-LuGqtOz4keZiaVC2RGajG-k,350
+flask_compress/__pycache__/__init__.cpython-311.pyc,,
+flask_compress/__pycache__/_version.cpython-311.pyc,,
+flask_compress/__pycache__/flask_compress.cpython-311.pyc,,
+flask_compress/_version.py,sha256=Xb3Nl3yRDciYSry8r5UKgCFucsMxLz6tgzaD0wNlnNk,21
+flask_compress/flask_compress.py,sha256=WxBbpJQ_ptsO0vhHF5jPDckxm7g6IXDgV-HGZ-0djOc,9494
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..849c87ed310d34aa5ff2d041345023ebd97b650a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Compress-1.15.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_compress
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..04463812d8c9852f8b999e62b7fdbd6fd345c302
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) 2011 Matthew Frazier
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..445a0b23ed2b7a814e8b29ac604d5b51f15c3640
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/METADATA
@@ -0,0 +1,183 @@
+Metadata-Version: 2.1
+Name: Flask-Login
+Version: 0.6.3
+Summary: User authentication and session management for Flask.
+Home-page: https://github.com/maxcountryman/flask-login
+Author: Matthew Frazier
+Author-email: leafstormrush@gmail.com
+Maintainer: Max Countryman
+License: MIT
+Project-URL: Documentation, https://flask-login.readthedocs.io/
+Project-URL: Changes, https://github.com/maxcountryman/flask-login/blob/main/CHANGES.md
+Project-URL: Source Code, https://github.com/maxcountryman/flask-login
+Project-URL: Issue Tracker, https://github.com/maxcountryman/flask-login/issues
+Classifier: Development Status :: 4 - Beta
+Classifier: Environment :: Web Environment
+Classifier: Framework :: Flask
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.7
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: Flask >=1.0.4
+Requires-Dist: Werkzeug >=1.0.1
+
+# Flask-Login
+
+
+[](https://coveralls.io/github/maxcountryman/flask-login?branch=main)
+[](LICENSE)
+
+Flask-Login provides user session management for Flask. It handles the common
+tasks of logging in, logging out, and remembering your users' sessions over
+extended periods of time.
+
+Flask-Login is not bound to any particular database system or permissions
+model. The only requirement is that your user objects implement a few methods,
+and that you provide a callback to the extension capable of loading users from
+their ID.
+
+## Installation
+
+Install the extension with pip:
+
+```sh
+$ pip install flask-login
+```
+
+## Usage
+
+Once installed, the Flask-Login is easy to use. Let's walk through setting up
+a basic application. Also please note that this is a very basic guide: we will
+be taking shortcuts here that you should never take in a real application.
+
+To begin we'll set up a Flask app:
+
+```python
+import flask
+
+app = flask.Flask(__name__)
+app.secret_key = 'super secret string' # Change this!
+```
+
+Flask-Login works via a login manager. To kick things off, we'll set up the
+login manager by instantiating it and telling it about our Flask app:
+
+```python
+import flask_login
+
+login_manager = flask_login.LoginManager()
+
+login_manager.init_app(app)
+```
+
+To keep things simple we're going to use a dictionary to represent a database
+of users. In a real application, this would be an actual persistence layer.
+However it's important to point out this is a feature of Flask-Login: it
+doesn't care how your data is stored so long as you tell it how to retrieve it!
+
+```python
+# Our mock database.
+users = {'foo@bar.tld': {'password': 'secret'}}
+```
+
+We also need to tell Flask-Login how to load a user from a Flask request and
+from its session. To do this we need to define our user object, a
+`user_loader` callback, and a `request_loader` callback.
+
+```python
+class User(flask_login.UserMixin):
+ pass
+
+
+@login_manager.user_loader
+def user_loader(email):
+ if email not in users:
+ return
+
+ user = User()
+ user.id = email
+ return user
+
+
+@login_manager.request_loader
+def request_loader(request):
+ email = request.form.get('email')
+ if email not in users:
+ return
+
+ user = User()
+ user.id = email
+ return user
+```
+
+Now we're ready to define our views. We can start with a login view, which will
+populate the session with authentication bits. After that we can define a view
+that requires authentication.
+
+```python
+@app.route('/login', methods=['GET', 'POST'])
+def login():
+ if flask.request.method == 'GET':
+ return '''
+
+ '''
+
+ email = flask.request.form['email']
+ if email in users and flask.request.form['password'] == users[email]['password']:
+ user = User()
+ user.id = email
+ flask_login.login_user(user)
+ return flask.redirect(flask.url_for('protected'))
+
+ return 'Bad login'
+
+
+@app.route('/protected')
+@flask_login.login_required
+def protected():
+ return 'Logged in as: ' + flask_login.current_user.id
+```
+
+Finally we can define a view to clear the session and log users out:
+
+```python
+@app.route('/logout')
+def logout():
+ flask_login.logout_user()
+ return 'Logged out'
+```
+
+We now have a basic working application that makes use of session-based
+authentication. To round things off, we should provide a callback for login
+failures:
+
+```python
+@login_manager.unauthorized_handler
+def unauthorized_handler():
+ return 'Unauthorized', 401
+```
+
+Documentation for Flask-Login is available on [ReadTheDocs](https://flask-login.readthedocs.io/en/latest/).
+For complete understanding of available configuration, please refer to the [source code](https://github.com/maxcountryman/flask-login).
+
+
+## Contributing
+
+We welcome contributions! If you would like to hack on Flask-Login, please
+follow these steps:
+
+1. Fork this repository
+2. Make your changes
+3. Install the dev requirements with `pip install -r requirements/dev.txt`
+4. Submit a pull request after running `tox` (ensure it does not error!)
+
+Please give us adequate time to review your submission. Thanks!
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..37b8816585903e42fd3297f72cbf0e35e8295b9a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/RECORD
@@ -0,0 +1,23 @@
+Flask_Login-0.6.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_Login-0.6.3.dist-info/LICENSE,sha256=ep37nF2iBO0TcPO2LBPimSoS2h2nB_R-FWiX7rQ0Tls,1059
+Flask_Login-0.6.3.dist-info/METADATA,sha256=AUSHR5Po6-Cwmz1KBrAZbTzR-iVVFvtb2NQKYl7UuAU,5799
+Flask_Login-0.6.3.dist-info/RECORD,,
+Flask_Login-0.6.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+Flask_Login-0.6.3.dist-info/WHEEL,sha256=Xo9-1PvkuimrydujYJAjF7pCkriuXBpUPEjma1nZyJ0,92
+Flask_Login-0.6.3.dist-info/top_level.txt,sha256=OuXmIpiFnXLvW-iBbW2km7ZIy5EZvwSBnYaOC3Kt7j8,12
+flask_login/__about__.py,sha256=Kkp5e9mV9G7vK_FqZof-g9RFmyyBzq1gge5aKXgvilE,389
+flask_login/__init__.py,sha256=wYQiQCikT_Ndp3PhOD-1gRTGCrUPIE-FrjQUrT9aVAg,2681
+flask_login/__pycache__/__about__.cpython-311.pyc,,
+flask_login/__pycache__/__init__.cpython-311.pyc,,
+flask_login/__pycache__/config.cpython-311.pyc,,
+flask_login/__pycache__/login_manager.cpython-311.pyc,,
+flask_login/__pycache__/mixins.cpython-311.pyc,,
+flask_login/__pycache__/signals.cpython-311.pyc,,
+flask_login/__pycache__/test_client.cpython-311.pyc,,
+flask_login/__pycache__/utils.cpython-311.pyc,,
+flask_login/config.py,sha256=YAocv18La7YGQyNY5aT7rU1GQIZnX6pvchwqx3kA9p8,1813
+flask_login/login_manager.py,sha256=h20F_iv3mqc6rIJ4-V6_XookzOUl8Rcpasua-dCByQY,20073
+flask_login/mixins.py,sha256=gPd7otMRljxw0eUhUMbHsnEBc_jK2cYdxg5KFLuJcoI,1528
+flask_login/signals.py,sha256=xCMoFHKU1RTVt1NY-Gfl0OiVKpiyNt6YJw_PsgkjY3w,2464
+flask_login/test_client.py,sha256=6mrjiBRLGJpgvvFlLypXPTBLiMp0BAN-Ft-uogqC81g,517
+flask_login/utils.py,sha256=Y1wxjCVxpYohBaQJ0ADLypQ-VvBNycwG-gVXFF7k99I,14021
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..ba48cbcf9275ac6d88fe25821695e14d0a822e79
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.41.3)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..31514bd20ce166ec4ec252051f2836a8200a2457
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Login-0.6.3.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_login
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..b6f9cdc4f542a8bb369ac3d68d0b923fcd2b7d89
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/LICENSE
@@ -0,0 +1,31 @@
+Copyright (c) 2010 by danjac.
+
+Some rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+* The names of the contributors may not be used to endorse or
+ promote products derived from this software without specific
+ prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..00b35c956a8e3f7bc7728bc34c2c5a08e6b40a3f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/METADATA
@@ -0,0 +1,35 @@
+Metadata-Version: 2.1
+Name: Flask-Mail
+Version: 0.9.1
+Summary: Flask extension for sending email
+Home-page: https://github.com/rduplain/flask-mail
+Author: Dan Jacob
+Author-email: danjac354@gmail.com
+Maintainer: Ron DuPlain
+Maintainer-email: ron.duplain@gmail.com
+License: BSD
+Platform: any
+Classifier: Development Status :: 4 - Beta
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+License-File: LICENSE
+Requires-Dist: Flask
+Requires-Dist: blinker
+
+
+Flask-Mail
+----------
+
+A Flask extension for sending email messages.
+
+Please refer to the online documentation for details.
+
+Links
+`````
+
+* `documentation `_
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..89d7fe44d4654b9bc41bc453bae0086d6f4df45c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/RECORD
@@ -0,0 +1,9 @@
+Flask_Mail-0.9.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_Mail-0.9.1.dist-info/LICENSE,sha256=4Rm-c4W3yEpsCANoWqvmytM2PUSFd7btDLd_SpVbEFQ,1449
+Flask_Mail-0.9.1.dist-info/METADATA,sha256=AllY2oEzc2vbZVrVjUpLq56-vHrqzCaemsVMQeWZPS8,995
+Flask_Mail-0.9.1.dist-info/RECORD,,
+Flask_Mail-0.9.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+Flask_Mail-0.9.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+Flask_Mail-0.9.1.dist-info/top_level.txt,sha256=DXVYMmoZEmH0LMYIpymMBM-ekAlhlAu1TCcWn2GM9OE,11
+__pycache__/flask_mail.cpython-311.pyc,,
+flask_mail.py,sha256=IHsiylgTIXOu6i0MQQcVGqBArCl9pR2XzkBMxj1_lr8,17950
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8a2934bbc3ef15c464ce05a56e8f4fbaec8dae32
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Mail-0.9.1.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_mail
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..2448fd2665df720101cf6662b17bfdfbda3e7cc3
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Miguel Grinberg
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..c0c67b93ef8bf46aa796b5a91e1149427e241b6f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/METADATA
@@ -0,0 +1,85 @@
+Metadata-Version: 2.1
+Name: Flask-Migrate
+Version: 4.0.7
+Summary: SQLAlchemy database migrations for Flask applications using Alembic.
+Author-email: Miguel Grinberg
+License: MIT
+Project-URL: Homepage, https://github.com/miguelgrinberg/flask-migrate
+Project-URL: Bug Tracker, https://github.com/miguelgrinberg/flask-migrate/issues
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 3
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Requires-Python: >=3.6
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: Flask >=0.9
+Requires-Dist: Flask-SQLAlchemy >=1.0
+Requires-Dist: alembic >=1.9.0
+
+Flask-Migrate
+=============
+
+[](https://github.com/miguelgrinberg/flask-migrate/actions)
+
+Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. The database operations are provided as command-line arguments under the `flask db` command.
+
+Installation
+------------
+
+Install Flask-Migrate with `pip`:
+
+ pip install Flask-Migrate
+
+Example
+-------
+
+This is an example application that handles database migrations through Flask-Migrate:
+
+```python
+from flask import Flask
+from flask_sqlalchemy import SQLAlchemy
+from flask_migrate import Migrate
+
+app = Flask(__name__)
+app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
+
+db = SQLAlchemy(app)
+migrate = Migrate(app, db)
+
+class User(db.Model):
+ id = db.Column(db.Integer, primary_key=True)
+ name = db.Column(db.String(128))
+```
+
+With the above application you can create the database or enable migrations if the database already exists with the following command:
+
+ $ flask db init
+
+Note that the `FLASK_APP` environment variable must be set according to the Flask documentation for this command to work. This will add a `migrations` folder to your application. The contents of this folder need to be added to version control along with your other source files.
+
+You can then generate an initial migration:
+
+ $ flask db migrate
+
+The migration script needs to be reviewed and edited, as Alembic currently does not detect every change you make to your models. In particular, Alembic is currently unable to detect indexes. Once finalized, the migration script also needs to be added to version control.
+
+Then you can apply the migration to the database:
+
+ $ flask db upgrade
+
+Then each time the database models change repeat the `migrate` and `upgrade` commands.
+
+To sync the database in another system just refresh the `migrations` folder from source control and run the `upgrade` command.
+
+To see all the commands that are available run this command:
+
+ $ flask db --help
+
+Resources
+---------
+
+- [Documentation](http://flask-migrate.readthedocs.io/en/latest/)
+- [pypi](https://pypi.python.org/pypi/Flask-Migrate)
+- [Change Log](https://github.com/miguelgrinberg/Flask-Migrate/blob/master/CHANGES.md)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..7bf330f7bd186603b1c5ed9cd2fb49be51910bdf
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/RECORD
@@ -0,0 +1,31 @@
+Flask_Migrate-4.0.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_Migrate-4.0.7.dist-info/LICENSE,sha256=kfkXGlJQvKy3Y__6tAJ8ynIp1HQfeROXhL8jZU1d-DI,1082
+Flask_Migrate-4.0.7.dist-info/METADATA,sha256=3WW5StkAdKx66iP12BXfTzoUsSB4rqEGxVs3qoollRg,3101
+Flask_Migrate-4.0.7.dist-info/RECORD,,
+Flask_Migrate-4.0.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+Flask_Migrate-4.0.7.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
+Flask_Migrate-4.0.7.dist-info/top_level.txt,sha256=jLoPgiMG6oR4ugNteXn3IHskVVIyIXVStZOVq-AWLdU,14
+flask_migrate/__init__.py,sha256=JMySGA55Y8Gxy3HviWu7qq5rPUNQBWc2NID2OicpDyw,10082
+flask_migrate/__pycache__/__init__.cpython-311.pyc,,
+flask_migrate/__pycache__/cli.cpython-311.pyc,,
+flask_migrate/cli.py,sha256=v1fOqjpUI8ZniSt0NAxdaU4gFMoZys5yLAofwmBdMHU,10689
+flask_migrate/templates/aioflask-multidb/README,sha256=Ek4cJqTaxneVjtkue--BXMlfpfp3MmJRjqoZvnSizww,43
+flask_migrate/templates/aioflask-multidb/__pycache__/env.cpython-311.pyc,,
+flask_migrate/templates/aioflask-multidb/alembic.ini.mako,sha256=SjYEmJKzz6K8QfuZWtLJAJWcCKOdRbfUhsVlpgv8ock,857
+flask_migrate/templates/aioflask-multidb/env.py,sha256=UcjeqkAbyUjTkuQFmCFPG7QOvqhco8-uGp8QEbto0T8,6573
+flask_migrate/templates/aioflask-multidb/script.py.mako,sha256=198VPxVEN3NZ3vHcRuCxSoI4XnOYirGWt01qkbPKoJw,1246
+flask_migrate/templates/aioflask/README,sha256=KKqWGl4YC2RqdOdq-y6quTDW0b7D_UZNHuM8glM1L-c,44
+flask_migrate/templates/aioflask/__pycache__/env.cpython-311.pyc,,
+flask_migrate/templates/aioflask/alembic.ini.mako,sha256=SjYEmJKzz6K8QfuZWtLJAJWcCKOdRbfUhsVlpgv8ock,857
+flask_migrate/templates/aioflask/env.py,sha256=m6ZtBhdpwuq89vVeLTWmNT-1NfJZqarC_hsquCdR9bw,3478
+flask_migrate/templates/aioflask/script.py.mako,sha256=8_xgA-gm_OhehnO7CiIijWgnm00ZlszEHtIHrAYFJl0,494
+flask_migrate/templates/flask-multidb/README,sha256=AfiP5foaV2odZxXxuUuSIS6YhkIpR7CsOo2mpuxwHdc,40
+flask_migrate/templates/flask-multidb/__pycache__/env.cpython-311.pyc,,
+flask_migrate/templates/flask-multidb/alembic.ini.mako,sha256=SjYEmJKzz6K8QfuZWtLJAJWcCKOdRbfUhsVlpgv8ock,857
+flask_migrate/templates/flask-multidb/env.py,sha256=F44iqsAxLTVBN_zD8CMUkdE7Aub4niHMmo5wl9mY4Uw,6190
+flask_migrate/templates/flask-multidb/script.py.mako,sha256=198VPxVEN3NZ3vHcRuCxSoI4XnOYirGWt01qkbPKoJw,1246
+flask_migrate/templates/flask/README,sha256=JL0NrjOrscPcKgRmQh1R3hlv1_rohDot0TvpmdM27Jk,41
+flask_migrate/templates/flask/__pycache__/env.cpython-311.pyc,,
+flask_migrate/templates/flask/alembic.ini.mako,sha256=SjYEmJKzz6K8QfuZWtLJAJWcCKOdRbfUhsVlpgv8ock,857
+flask_migrate/templates/flask/env.py,sha256=ibK1hsdOsOBzXNU2yQoAIza7f_EFzaVSWwON_NSpNzQ,3344
+flask_migrate/templates/flask/script.py.mako,sha256=8_xgA-gm_OhehnO7CiIijWgnm00ZlszEHtIHrAYFJl0,494
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..98c0d20b7a64f4f998d7913e1d38a05dba20916c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.42.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0652762c7b98cd2758190e2dadd48dcd1cc158a3
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Migrate-4.0.7.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_migrate
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..7e5f09ef8fa885a8ccb5da94a777e40edf3eac51
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2017 Miguel Grinberg
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..8da7207cc42ffe659ff37f499576b33563ac520d
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/METADATA
@@ -0,0 +1,61 @@
+Metadata-Version: 2.1
+Name: Flask-Paranoid
+Version: 0.3.0
+Summary: Simple user session protection
+Home-page: https://github.com/miguelgrinberg/flask-paranoid
+Author: Miguel Grinberg
+Author-email: miguel.grinberg@gmail.com
+License: UNKNOWN
+Project-URL: Bug Tracker, https://github.com/miguelgrinberg/flask-paranoid/issues
+Platform: UNKNOWN
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 3
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Requires-Python: >=3.6
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: Flask (>=0.10)
+
+flask-paranoid
+==============
+
+[](https://github.com/miguelgrinberg/flask-paranoid/actions) [](https://codecov.io/gh/miguelgrinberg/flask-paranoid)
+
+Simple user session protection.
+
+Quick Start
+-----------
+
+Here is a simple application that uses Flask-Paranoid to protect the user session:
+
+```python
+from flask import Flask
+from flask_paranoid import Paranoid
+
+app = Flask(__name__)
+app.config['SECRET_KEY'] = 'top-secret!'
+
+paranoid = Paranoid(app)
+paranoid.redirect_view = '/'
+
+@app.route('/')
+def index():
+ return render_template('index.html')
+```
+
+When a client connects to this application, a "paranoid" token will be
+generated according to the IP address and user agent. In all subsequent
+requests, the token will be recalculated and checked against the one computed
+for the first request. If the session cookie is stolen and the attacker tries
+to use it from another location, the generated token will be different, and in
+that case the extension will clear the session and block the request.
+
+Resources
+---------
+
+- [Documentation](http://pythonhosted.org/Flask-Paranoid)
+- [PyPI](https://pypi.python.org/pypi/flask-paranoid)
+- [Change Log](https://github.com/miguelgrinberg/flask-paranoid/blob/main/CHANGES.md)
+
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..5b1b91ec44c54f658304f705c37d031208028fd2
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/RECORD
@@ -0,0 +1,11 @@
+Flask_Paranoid-0.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_Paranoid-0.3.0.dist-info/LICENSE,sha256=BoM_-PG_Gi_T2-HnzcfbRNxPAopEoagjLC8tOUXrXoI,1082
+Flask_Paranoid-0.3.0.dist-info/METADATA,sha256=OhAKEvvj7JejqKbIKcVydpo3T-kHBTOGpSo4zS0SIxU,2053
+Flask_Paranoid-0.3.0.dist-info/RECORD,,
+Flask_Paranoid-0.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+Flask_Paranoid-0.3.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
+Flask_Paranoid-0.3.0.dist-info/top_level.txt,sha256=S6nnymnJwQ4ClN4d5yPJUn64L6rCSJwt44T8fYfwDbI,15
+flask_paranoid/__init__.py,sha256=xsOm_1swS_kacnLyEsLe2cynVxzdGllju0HRx8GHH0o,45
+flask_paranoid/__pycache__/__init__.cpython-311.pyc,,
+flask_paranoid/__pycache__/paranoid.cpython-311.pyc,,
+flask_paranoid/paranoid.py,sha256=bHgq04WSh-6uq-qXdaP3A8w1gTbW3swd8z9KOLlHPOM,4326
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..becc9a66ea739ba941d48a749e248761cc6e658a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.37.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1972e0a113c76c3439e4e2e5b522824077a721da
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Paranoid-0.3.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_paranoid
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..38eeb7659ba7e09c9526aa3dde989944ec8f9afa
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/METADATA
@@ -0,0 +1,36 @@
+Metadata-Version: 2.1
+Name: Flask-Principal
+Version: 0.4.0
+Summary: Identity management for flask
+Home-page: http://packages.python.org/Flask-Principal/
+Author: Ali Afshar
+Author-email: aafshar@gmail.com
+Maintainer: Matt Wright
+Maintainer-email: matt@nobien.net
+License: MIT
+Platform: any
+Classifier: Development Status :: 4 - Beta
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Dist: Flask
+Requires-Dist: blinker
+
+
+Flask Principal
+---------------
+
+Identity management for Flask.
+
+Links
+`````
+
+* `documentation `_
+* `source `_
+* `development version
+ `_
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..51d876fb3f3115cb0764975dc1addda6aebc77ea
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/RECORD
@@ -0,0 +1,7 @@
+Flask_Principal-0.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_Principal-0.4.0.dist-info/METADATA,sha256=8eUbgL4RZ7o1VIa0OeW7U2w5OA35XNKyR3ji80NTyQU,1092
+Flask_Principal-0.4.0.dist-info/RECORD,,
+Flask_Principal-0.4.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+Flask_Principal-0.4.0.dist-info/top_level.txt,sha256=OvvQEFZouL0A8O9TdIg_v6TAOLNnvaFr34Zr28AqBGY,16
+__pycache__/flask_principal.cpython-311.pyc,,
+flask_principal.py,sha256=H-6ZuSY_nAYfWd-VdojVZuwVLV_tXkUwTwThKdnHunQ,13860
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7ab03f437033e77098f2a6e957840f95a1d29a48
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Principal-0.4.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_principal
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/AUTHORS b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..3bfdb7296392c94d1f4b3f2f583513e53340c681
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/AUTHORS
@@ -0,0 +1,53 @@
+Flask-Security was written by Matt Wright and various contributors.
+
+Flask-Security-Too is an independently maintained repo:
+
+Development Lead
+````````````````
+
+- Chris Wagner
+
+Maintainer
+``````````
+
+- Chris Wagner
+
+Patches and Suggestions
+```````````````````````
+
+Alexander Sukharev
+Alexey Poryadin
+Andrew J. Camenga
+Anthony Plunkett
+Artem Andreev
+Catherine Wise
+Chris Haines
+Christophe Simonis
+David Ignacio
+Eric Butler
+Eskil Heyn Olsen
+Iuri de Silvio
+Jay Goel
+Jiri Kuncar
+Joe Esposito
+Joe Hand
+Josh Purvis
+Kostyantyn Leschenko
+Luca Invernizzi
+Manuel Ebert
+Martin Maillard
+Paweł Krześniak
+Robert Clark
+Rodrigue Cloutier
+Rotem Yaari
+Srijan Choudhary
+Tristan Escalada
+Vadim Kotov
+Walt Askew
+John Paraskevopoulos
+Chris Wagner
+Eric Regnier
+Gal Stainfeld
+Ivan Piskunov
+Tyler Baur
+Glenn Lehman
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..d165be9a2bc537b31602542daede5c9875a7cfb1
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (C) 2012-2021 by Matthew Wright
+Copyright (C) 2019-2024 by Chris Wagner
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..2a28dc5d44f3b00db83c2e1ff2ea50a345ab85de
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/METADATA
@@ -0,0 +1,176 @@
+Metadata-Version: 2.1
+Name: Flask-Security-Too
+Version: 5.4.3
+Summary: Quickly add security features to your Flask application.
+Author: Matt Wright
+Author-email: Chris Wagner
+Maintainer-email: Chris Wagner
+Project-URL: Documentation, https://flask-security-too.readthedocs.io
+Project-URL: Homepage, https://github.com/Flask-Middleware/flask-security
+Project-URL: Source, https://github.com/Flask-Middleware/flask-security
+Project-URL: Tracker, https://github.com/Flask-Middleware/flask-security/issues
+Project-URL: Releases, https://pypi.org/project/Flask-Security-Too/
+Keywords: flask security
+Classifier: Environment :: Web Environment
+Classifier: Framework :: Flask
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Development Status :: 5 - Production/Stable
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+License-File: AUTHORS
+Requires-Dist: Flask >=2.3.2
+Requires-Dist: Flask-Login >=0.6.2
+Requires-Dist: Flask-Principal >=0.4.0
+Requires-Dist: Flask-WTF >=1.1.2
+Requires-Dist: email-validator >=2.0.0
+Requires-Dist: markupsafe >=2.1.0
+Requires-Dist: passlib >=1.7.4
+Requires-Dist: wtforms >=3.0.0
+Requires-Dist: importlib-resources >=5.10.0
+Provides-Extra: babel
+Requires-Dist: babel >=2.12.1 ; extra == 'babel'
+Requires-Dist: flask-babel >=3.1.0 ; extra == 'babel'
+Provides-Extra: common
+Requires-Dist: bcrypt >=4.0.1 ; extra == 'common'
+Requires-Dist: flask-mailman >=0.3.0 ; extra == 'common'
+Requires-Dist: bleach >=6.0.0 ; extra == 'common'
+Provides-Extra: fsqla
+Requires-Dist: flask-sqlalchemy >=3.0.3 ; extra == 'fsqla'
+Requires-Dist: sqlalchemy >=2.0.12 ; extra == 'fsqla'
+Requires-Dist: sqlalchemy-utils >=0.41.1 ; extra == 'fsqla'
+Provides-Extra: low
+Requires-Dist: Flask ==2.3.2 ; extra == 'low'
+Requires-Dist: Flask-SQLAlchemy ==3.0.3 ; extra == 'low'
+Requires-Dist: Flask-Babel ==3.1.0 ; extra == 'low'
+Requires-Dist: Flask-Mailman ==0.3.0 ; extra == 'low'
+Requires-Dist: Flask-Login ==0.6.2 ; extra == 'low'
+Requires-Dist: Flask-WTF ==1.1.2 ; extra == 'low'
+Requires-Dist: peewee ==3.16.2 ; extra == 'low'
+Requires-Dist: argon2-cffi ==21.3.0 ; extra == 'low'
+Requires-Dist: authlib ==1.2.0 ; extra == 'low'
+Requires-Dist: babel ==2.12.1 ; extra == 'low'
+Requires-Dist: bcrypt ==4.0.1 ; extra == 'low'
+Requires-Dist: bleach ==6.0.0 ; extra == 'low'
+Requires-Dist: freezegun ; extra == 'low'
+Requires-Dist: jinja2 ==3.1.2 ; extra == 'low'
+Requires-Dist: itsdangerous ==2.1.2 ; extra == 'low'
+Requires-Dist: markupsafe ==2.1.2 ; extra == 'low'
+Requires-Dist: mongoengine ==0.27.0 ; extra == 'low'
+Requires-Dist: mongomock ==4.1.2 ; extra == 'low'
+Requires-Dist: phonenumberslite ==8.13.11 ; extra == 'low'
+Requires-Dist: qrcode ==7.4.2 ; extra == 'low'
+Requires-Dist: requests ; extra == 'low'
+Requires-Dist: setuptools ; extra == 'low'
+Requires-Dist: sqlalchemy ==2.0.12 ; extra == 'low'
+Requires-Dist: sqlalchemy-utils ==0.41.1 ; extra == 'low'
+Requires-Dist: webauthn ==2.0.0 ; extra == 'low'
+Requires-Dist: werkzeug ==2.3.3 ; extra == 'low'
+Requires-Dist: zxcvbn ==4.4.28 ; extra == 'low'
+Requires-Dist: pony ==0.7.16 ; (python_version < "3.11") and extra == 'low'
+Provides-Extra: mfa
+Requires-Dist: cryptography >=40.0.2 ; extra == 'mfa'
+Requires-Dist: qrcode >=7.4.2 ; extra == 'mfa'
+Requires-Dist: phonenumberslite >=8.13.11 ; extra == 'mfa'
+Requires-Dist: webauthn >=2.0.0 ; extra == 'mfa'
+
+Flask-Security
+===================
+
+.. image:: https://github.com/Flask-Middleware/flask-security/workflows/tests/badge.svg?branch=master&event=push
+ :target: https://github.com/Flask-Middleware/flask-security
+
+.. image:: https://codecov.io/gh/Flask-Middleware/flask-security/branch/master/graph/badge.svg?token=U02MUQJ7BM
+ :target: https://codecov.io/gh/Flask-Middleware/flask-security
+ :alt: Coverage!
+
+.. image:: https://img.shields.io/github/tag/Flask-Middleware/flask-security.svg
+ :target: https://github.com/Flask-Middleware/flask-security/releases
+
+.. image:: https://img.shields.io/pypi/dm/flask-security-too.svg
+ :target: https://pypi.python.org/pypi/flask-security-too
+ :alt: Downloads
+
+.. image:: https://img.shields.io/github/license/Flask-Middleware/flask-security.svg
+ :target: https://github.com/Flask-Middleware/flask-security/blob/master/LICENSE
+ :alt: License
+
+.. image:: https://readthedocs.org/projects/flask-security-too/badge/?version=latest
+ :target: https://flask-security-too.readthedocs.io/en/latest/?badge=latest
+ :alt: Documentation Status
+
+.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
+ :target: https://github.com/python/black
+
+.. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white
+ :target: https://github.com/pre-commit/pre-commit
+ :alt: pre-commit
+
+Quickly add security features to your Flask application.
+
+Notes on this repo
+------------------
+This is an independently maintained version of Flask-Security forked from the 3.0.0
+version of the `Original `_
+
+Goals
++++++
+* Regain momentum for this critical piece of the Flask eco-system. To that end the
+ the plan is to put out small, frequent releases starting with pulling the simplest
+ and most obvious changes that have already been vetted in the upstream version, as
+ well as other pull requests. This was completed with the June 29 2019 3.2.0 release.
+* Continue work to get Flask-Security to be usable from Single Page Applications,
+ such as those built with Vue and Angular, that have no html forms. This is true as of the 3.3.0
+ release.
+* Use `OWASP `_ to guide best practice and default configurations.
+* Be more opinionated and 'batteries' included by reducing reliance on abandoned projects and
+ bundling in support for common use cases.
+* Follow the `Pallets `_ lead on supported versions, documentation
+ standards and any other guidelines for extensions that they come up with.
+* Continue to add newer authentication/authorization standards:
+ * 'Social Auth' integrated (using authlib) (5.1)
+ * WebAuthn support (5.0)
+ * Two-Factor recovery codes (5.0)
+ * First-class support for username as identity (4.1)
+ * Support for fresheness decorator to ensure sensitive operations have new authentication (4.0)
+ * Support for email normalization and validation (4.0)
+ * Unified signin (username, phone, passwordless) feature (3.4)
+
+
+Contributing
+++++++++++++
+Issues and pull requests are welcome. Other maintainers are also welcome. Unlike
+the original Flask-Security - issue pull requests against the *master* branch.
+Please consult these `contributing`_ guidelines.
+
+.. _contributing: https://github.com/Flask-Middleware/flask-security/blob/master/CONTRIBUTING.rst
+
+Installing
+----------
+Install and update using `pip `_:
+
+::
+
+ pip install -U Flask-Security-Too
+
+
+Resources
+---------
+
+- `Documentation `_
+- `Releases `_
+- `Issue Tracker `_
+- `Code `_
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..5a2193358d796d334e1e45f435b5f76fbcbb036a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/RECORD
@@ -0,0 +1,166 @@
+Flask_Security_Too-5.4.3.dist-info/AUTHORS,sha256=PhS-KLT1PE_6AC-y3AbladBMy_LJHFzzC8kK6U7MykQ,834
+Flask_Security_Too-5.4.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_Security_Too-5.4.3.dist-info/LICENSE,sha256=0o1it6JJdv8gaDLnUDD2NPvlo1ATFjPHkHvwzmPsOOU,1119
+Flask_Security_Too-5.4.3.dist-info/METADATA,sha256=IxzasWDjFTOi-M1Wi9Oo_Fb4slGpjnMS26jzoE7a4ok,7975
+Flask_Security_Too-5.4.3.dist-info/RECORD,,
+Flask_Security_Too-5.4.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+Flask_Security_Too-5.4.3.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+Flask_Security_Too-5.4.3.dist-info/top_level.txt,sha256=32qbHJfRj6C-_wcbEzQlmEZq9lpS9hdLErS8F5DNQ38,15
+flask_security/__init__.py,sha256=MrUg6qBIzR48iGQYhks0CECmAHehFjWkNBoHKN2JvkE,3236
+flask_security/__pycache__/__init__.cpython-311.pyc,,
+flask_security/__pycache__/babel.cpython-311.pyc,,
+flask_security/__pycache__/changeable.cpython-311.pyc,,
+flask_security/__pycache__/cli.cpython-311.pyc,,
+flask_security/__pycache__/confirmable.cpython-311.pyc,,
+flask_security/__pycache__/core.cpython-311.pyc,,
+flask_security/__pycache__/datastore.cpython-311.pyc,,
+flask_security/__pycache__/decorators.cpython-311.pyc,,
+flask_security/__pycache__/forms.cpython-311.pyc,,
+flask_security/__pycache__/json.cpython-311.pyc,,
+flask_security/__pycache__/mail_util.cpython-311.pyc,,
+flask_security/__pycache__/oauth_glue.cpython-311.pyc,,
+flask_security/__pycache__/oauth_provider.cpython-311.pyc,,
+flask_security/__pycache__/password_util.cpython-311.pyc,,
+flask_security/__pycache__/passwordless.cpython-311.pyc,,
+flask_security/__pycache__/phone_util.cpython-311.pyc,,
+flask_security/__pycache__/proxies.cpython-311.pyc,,
+flask_security/__pycache__/quart_compat.cpython-311.pyc,,
+flask_security/__pycache__/recoverable.cpython-311.pyc,,
+flask_security/__pycache__/recovery_codes.cpython-311.pyc,,
+flask_security/__pycache__/registerable.cpython-311.pyc,,
+flask_security/__pycache__/signals.cpython-311.pyc,,
+flask_security/__pycache__/tf_plugin.cpython-311.pyc,,
+flask_security/__pycache__/totp.cpython-311.pyc,,
+flask_security/__pycache__/twofactor.cpython-311.pyc,,
+flask_security/__pycache__/unified_signin.cpython-311.pyc,,
+flask_security/__pycache__/username_util.cpython-311.pyc,,
+flask_security/__pycache__/utils.cpython-311.pyc,,
+flask_security/__pycache__/views.cpython-311.pyc,,
+flask_security/__pycache__/webauthn.cpython-311.pyc,,
+flask_security/__pycache__/webauthn_util.cpython-311.pyc,,
+flask_security/babel.py,sha256=JI4D0CmO1cqNYLsQcZQTw74japxNTGSoRrAZI2BcQmY,3879
+flask_security/changeable.py,sha256=B14N8OIGmCrgQzp5DbZvz5q6CIJkz9s0HTfABiMwQIA,2982
+flask_security/cli.py,sha256=fzhFq_ajvhZTOjEe6CCMaBmVv2e6FCcz5y6MmPZpJEk,10682
+flask_security/confirmable.py,sha256=BEh6-XfsCdSJwedX3FJ_KLKxXbJPI9nw6hYFAkm3oZY,2870
+flask_security/core.py,sha256=8w8wEQ7C2dOzT1_ZZZSKGSmZwo2ALfsvvrYMIlCcH8M,77194
+flask_security/datastore.py,sha256=eTN2EKhDtAxzmOLJurPyt91jTAOQvxeG3m9n2KH0SP8,40011
+flask_security/decorators.py,sha256=1jxWKi2UqSP7o-ddvcDKUMM5v08ZlqVMqMPSUI1ZJC4,23292
+flask_security/forms.py,sha256=hEzQy_crrI8sX2Qfgiyht2X9bSppiosEePHgmKNShXU,31475
+flask_security/json.py,sha256=rLno0eSzGodzu95y1r1BS2zdKcAcjFEtB_4gKGlUeJE,803
+flask_security/mail_util.py,sha256=2rEAWt5NWyO171yWUI4fanqgm5sjH7qXqUEi8k9eHDw,5980
+flask_security/models/__init__.py,sha256=coWZEC0ax0yZTegrfhpV5hZhfNy6Lqamfyw2AGe65hI,436
+flask_security/models/__pycache__/__init__.cpython-311.pyc,,
+flask_security/models/__pycache__/fsqla.cpython-311.pyc,,
+flask_security/models/__pycache__/fsqla_v2.cpython-311.pyc,,
+flask_security/models/__pycache__/fsqla_v3.cpython-311.pyc,,
+flask_security/models/fsqla.py,sha256=dTEtRkeZmxAoC8cmhBk-YZiM3yguR-Rn0LurtvDs-_o,4008
+flask_security/models/fsqla_v2.py,sha256=0R_e-iy-sKR2dkzp5Wtcu74YcTvSW6iV6o4Lb-UTGgs,1432
+flask_security/models/fsqla_v3.py,sha256=Drr_IDetiub4a1uscmRhEH48oXuNXvRYzmPV3oZP9H8,3607
+flask_security/oauth_glue.py,sha256=ja0rSUkoz0KFFxflQbpQEOhre8AIHvWnrq1yLAAZQh8,9267
+flask_security/oauth_provider.py,sha256=Hd5x5SjADJ0iit95CQruIyzOA7FPHMTpPWZ-JntOrlI,4348
+flask_security/password_util.py,sha256=8BDw6LxV-WObL76fBqi-i1rdKxP9WeL5epzhr36APXo,2323
+flask_security/passwordless.py,sha256=woYRZlfulpVRenxy3u8k5a_KSx89aYlmKTkisbPXJ68,1593
+flask_security/phone_util.py,sha256=fuvHItd5gZ0BFVXsYLnx9__g_Olx9fGVfpWVV45XCiY,2408
+flask_security/proxies.py,sha256=97f4uz2apyF2C98eNVMJzqlTpENyZETIJMSFzgsbpVo,788
+flask_security/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+flask_security/quart_compat.py,sha256=YDb60Guf2pZ74loH7MlDdkrK4ghUoI9hIF0Ul1uCro4,923
+flask_security/recoverable.py,sha256=M6gdhvBwmLt__IN5mr_iesvcSKLZlFwsHfiAHsvcPaQ,3530
+flask_security/recovery_codes.py,sha256=ZleaPzJ7WhEjn1WSGghtgNZs75KZhmnWVuXWENs-9hA,8355
+flask_security/registerable.py,sha256=q4yAm8SkMPQG89bti7LcJmiyGIJM0KnMGUdPXgliyzc,6359
+flask_security/signals.py,sha256=WgdBieVSmGgE-HXU6QZtG7a93hjQ5nDRvxpAJzs9JpI,1439
+flask_security/static/js/base64.js,sha256=QRosC0_HfAja_USffcwGTqczjJtktjeA2NaUcG-bqA0,4042
+flask_security/static/js/webauthn.js,sha256=hrLvAuHbnK1qaDZYo_KVWHEtTItRHwK5Y3pQGR05rVI,6633
+flask_security/templates/security/_macros.html,sha256=7ZfoYDxeM3JvodC0bJ__HKXU1NnOaEVoKyM-m2_MEQo,1224
+flask_security/templates/security/_menu.html,sha256=alCbcMvfQNf25ZwXdBM22XqyhQA5C6WFcdqHhpUhulQ,2324
+flask_security/templates/security/_messages.html,sha256=K8fVuxJBnSh1yOqNMn_xeZSa9AmJFtPtDk-GmB2fgcs,267
+flask_security/templates/security/base.html,sha256=CToxhhaJFA8x3KMUQykFsmA1COBnl7u5Q9_eDBW4dvI,1134
+flask_security/templates/security/change_password.html,sha256=lJKA5Opl0YZd2aYhURIf1bjwyURDsfpgLTzNTUrIaXg,979
+flask_security/templates/security/email/change_notice.html,sha256=7piNfDCtwL8Ch5G63kSkjeJxdN6Ba5-cWzkFTe8uugg,288
+flask_security/templates/security/email/change_notice.txt,sha256=HlckmPvEpFLyldED1EyYJxbQL84F1VOrkcLeDbCa3dI,241
+flask_security/templates/security/email/confirmation_instructions.html,sha256=Dga71RUKSLtRfzW0Ueuhqb8jQWHZcZtSTc0Vrz9q44Q,500
+flask_security/templates/security/email/confirmation_instructions.txt,sha256=7MSL2ASMRm9C8nIRn3HJhMqZImlzO0Ri7rR8fV7QMCM,431
+flask_security/templates/security/email/login_instructions.html,sha256=PHw3wzTPYSMEYYveG4HPQLAssY_9j0AnKiW9VU_liBY,214
+flask_security/templates/security/email/login_instructions.txt,sha256=BAm_dakwyhRWc0pQYung6hOe-HtEEIoPCiNw0xAU7wM,148
+flask_security/templates/security/email/reset_instructions.html,sha256=zyhMuVivW9rbudXy8C6T9tp-CvnJ-26HeYRUiEhExSM,409
+flask_security/templates/security/email/reset_instructions.txt,sha256=R_LkrW_s9wvXSw3uYCM8goUiEUoYQWe_BHTDO9aZfXM,396
+flask_security/templates/security/email/reset_notice.html,sha256=TLS_B1d4ug7lO9lkaKpb3nnaiJp09-3Eihce06DJMuY,55
+flask_security/templates/security/email/reset_notice.txt,sha256=Q2Ps30ZozZWQot10yFUjMXt80TLsg371YQbboMHumpo,48
+flask_security/templates/security/email/two_factor_instructions.html,sha256=MqPJVX3TM6VWzyAHPobXTpX3EI7piDLMXgimsVNDJKE,144
+flask_security/templates/security/email/two_factor_instructions.txt,sha256=O7lT80J0s5M7phdpJnGW7eVjPa-TDHSX37xYzcByjbY,131
+flask_security/templates/security/email/two_factor_rescue.html,sha256=-bvdsKsRTNUiGFJpPOuySsRXe3Fw0nujdDoGRHbCLtY,71
+flask_security/templates/security/email/two_factor_rescue.txt,sha256=CzcLtzXbl2XArt-7Vj31602ay_f-XPgkB3ED1oJs7YM,64
+flask_security/templates/security/email/us_instructions.html,sha256=WlZHosJRwQKxfY5UXQt-ByVCUVmbOJ917Yd7Fx8cTqU,639
+flask_security/templates/security/email/us_instructions.txt,sha256=LX0-OGzvsaeaqn_dl4hvCkgisvhyyzIleESFgpNZdPM,570
+flask_security/templates/security/email/welcome.html,sha256=xo1mLukuOmIVcqRYnSOsstLptAOm0N_G_Wu22SgNlFo,614
+flask_security/templates/security/email/welcome.txt,sha256=3kBO-n5W3W8HZwLcVJtNWeI0l7xcSDm3EmuOZp-nq6o,531
+flask_security/templates/security/email/welcome_existing.html,sha256=rkUC4iHu85C4k4Nqt0kCZvpNCfV3ykxnQgnp3cbln5w,888
+flask_security/templates/security/email/welcome_existing.txt,sha256=xkDTAyLJxLEkW-YqlR0WnlEiLp_mM6-MQiVVT07mxjQ,795
+flask_security/templates/security/email/welcome_existing_username.html,sha256=r-feN0xrhVzJl9dHIdi2nh9yqYutHOKHhw0c55TR5Mg,658
+flask_security/templates/security/email/welcome_existing_username.txt,sha256=4xiUNqEoNU53MAOx-3QQoEOjMZz80_Cn2V9P_9I48b8,625
+flask_security/templates/security/forgot_password.html,sha256=bgoH_g5h9ZMJWi_Qh2vqDFOBv9WuWMZkTznspM-IRA8,729
+flask_security/templates/security/login_user.html,sha256=VaZyIXRX4mRXKZbtogXpkX4IJEVWqMbs7kXncKAgOxs,2274
+flask_security/templates/security/mf_recovery.html,sha256=jden_1kC07tDKiZK9Vkb7G-LQ-roAcp4glsLuYDRwlo,540
+flask_security/templates/security/mf_recovery_codes.html,sha256=0jUGgoO6TjrKd1WvmKRRsuviszLiR3JNZLpnYfEo66Q,1172
+flask_security/templates/security/register_user.html,sha256=q1gRtsmwAL2CWgYp2CgHE69LKBxkp22fdZwI_ZjSBtc,1007
+flask_security/templates/security/reset_password.html,sha256=sfUIJZ_QSjr05jG5kr1PIGyo3xlZKlIl0nlWG1mNaJk,808
+flask_security/templates/security/send_confirmation.html,sha256=xcJVK3BPC6fu8TTO3eygVGRacFdCLVc_zagnL8ah1Qw,584
+flask_security/templates/security/send_login.html,sha256=6owz5E9GfMQMD8ZxBIyQ3Um3R561CE4vuVgsyBwHfJM,517
+flask_security/templates/security/two_factor_select.html,sha256=2kfP5hb8LdEw-mTnIfFqhSsNTxUe_EcfgkahL0JxivQ,583
+flask_security/templates/security/two_factor_setup.html,sha256=ST-Vdcl2u4yD-YKfjHFMkUFPfN2hzz-uT1hiwmGkJgU,4113
+flask_security/templates/security/two_factor_verify_code.html,sha256=nELAXZCdNSu-7cq2IWgDvK60kHTjMty2eb2dDs2_nH4,1522
+flask_security/templates/security/us_setup.html,sha256=TpZ6ISO1pn31ZOqTrS87zR_7q9hagDq0DJHJVrVRjzY,4179
+flask_security/templates/security/us_signin.html,sha256=NakkqVKdAnB4v3MIlJuminUp5Sxcga7sWdI0DCo_Dig,2367
+flask_security/templates/security/us_verify.html,sha256=8ZaviOKU9cFX45f3uh3B5KBZv-KJXpj06ITKi7QKBOU,1542
+flask_security/templates/security/verify.html,sha256=hianwnYLB534FosJnXjOyYHFkzAztZJsfyl4UnSm33E,882
+flask_security/templates/security/wan_register.html,sha256=Mz_7SoPcB_TW01m6TzZUxFXsxE5ffrFxPE77FvVWo7Q,3668
+flask_security/templates/security/wan_signin.html,sha256=fU__9ey40UJTLvgGIVrS2_mp3EU-z1OzUx3M9Xr-6Y0,2701
+flask_security/templates/security/wan_verify.html,sha256=_5q3mUX1FkAj9JoIykapU54LVfU2XEHz-XMAajuhsUE,2053
+flask_security/tf_plugin.py,sha256=MTqjab7Mc0Md5X3--CPnjbbtzHGdxe2bn9EBeLRjf_I,12563
+flask_security/totp.py,sha256=vX9ZUTMCkcxO8DlbG2VAM0NSD7vfl9OZbVOM-Ws5tAU,6732
+flask_security/translations/af_ZA/LC_MESSAGES/flask_security.mo,sha256=YvHY8W4uCZu3LlzzNpeay_09yHI4wVEUrRowCIJyDJo,9761
+flask_security/translations/af_ZA/LC_MESSAGES/flask_security.po,sha256=5h8GpVQTyNn4OICEv1bjKSTe9S91va6F3PkM2calS4A,32984
+flask_security/translations/ca_ES/LC_MESSAGES/flask_security.mo,sha256=j5k0U-SxoEwc1BeXFna192Cq90olmuwTTA2XNA05H7s,5834
+flask_security/translations/ca_ES/LC_MESSAGES/flask_security.po,sha256=1ME7J4ShOD2iathr1RHLVR1ScXmD4jDbTZN0sJIRVKs,31374
+flask_security/translations/da_DK/LC_MESSAGES/flask_security.mo,sha256=RZ9HMpmx-sT_tD9dbBlZwHK5dLDyjv7h-sVhdSBox-M,5407
+flask_security/translations/da_DK/LC_MESSAGES/flask_security.po,sha256=DHCVBILnAUu68XxteR6_8luVcxiUOYX7lAWacU3HHGs,30861
+flask_security/translations/de_DE/LC_MESSAGES/flask_security.mo,sha256=jXWlCfWe6yq9jtxxbRULUuv1cbE36YhFk8wsN7cCPTQ,20662
+flask_security/translations/de_DE/LC_MESSAGES/flask_security.po,sha256=gPlLF-gftm918xu4yGjwObfcBiQTHo7zoWsUMzJBFUk,39619
+flask_security/translations/es_ES/LC_MESSAGES/flask_security.mo,sha256=flzvRrCjmIg-WIZRVYiaONXusKVIg9X3k67MjLlmWo8,22381
+flask_security/translations/es_ES/LC_MESSAGES/flask_security.po,sha256=MlJa3y7jnKRI5EMNpxQZP0-_F6o0d7eoqXhUqnPH_BY,36472
+flask_security/translations/eu_ES/LC_MESSAGES/flask_security.mo,sha256=IsUZ979vYZoQ8wyJG8EnH6ff-_wHp311QwLMsCPvVpc,11454
+flask_security/translations/eu_ES/LC_MESSAGES/flask_security.po,sha256=k1xF-NSMBBVcWZzbFnjRMZ-J2vifsSzExkbgt0oc2Eg,33962
+flask_security/translations/flask_security.pot,sha256=WiRdoASI9dHyZTTcmdeBJ-p8iZHWqGZmrUsVr6rCduQ,26090
+flask_security/translations/fr_FR/LC_MESSAGES/flask_security.mo,sha256=EpM9oAkmAwnYh-fmxwEEUhSZqeCrZH07H1wNRQRkX8Y,11273
+flask_security/translations/fr_FR/LC_MESSAGES/flask_security.po,sha256=uVONTLjfMNe8YtFF8Vr1-DtKMgZRaRVq9cHIBI-Ql6k,32911
+flask_security/translations/hu_HU/LC_MESSAGES/flask_security.mo,sha256=BiqbYy07NdQPZ1sDMm_WW3YGpY5kL9_98WbU9B6D1O4,19123
+flask_security/translations/hu_HU/LC_MESSAGES/flask_security.po,sha256=8ztUK_UQiMB7Eds3_1DLeM-SwyEa0kWyHlaDPiXM8g0,36505
+flask_security/translations/hy_AM/LC_MESSAGES/flask_security.mo,sha256=QSZdypA4q0pEPLri19Ffd_13NmovISz3hPsVbJldFFU,26595
+flask_security/translations/hy_AM/LC_MESSAGES/flask_security.po,sha256=QOwdIGjEedUm-wmPTVoD8GoSXcqS4gTUWlyh2FpbqeE,42983
+flask_security/translations/is_IS/LC_MESSAGES/flask_security.mo,sha256=-DbFNNBkX_h7WKgIUhuTI-kzDpYDicdpvEb8fdt0d9Q,6649
+flask_security/translations/is_IS/LC_MESSAGES/flask_security.po,sha256=HO3ITYNUTu0iJfOCNzQEfXApXyAPIVpldf4iQuHv29k,30509
+flask_security/translations/it_IT/LC_MESSAGES/flask_security.mo,sha256=qakWnOCiK-jyKJYpZ4lFByAO91iZiDFdl2Xpbvf52So,21541
+flask_security/translations/it_IT/LC_MESSAGES/flask_security.po,sha256=7c-dHQAqJ_DvJGopWeWEmiw4iAd_TuTiYrMAFdqw0iE,35521
+flask_security/translations/ja_JP/LC_MESSAGES/flask_security.mo,sha256=Y-ryx9ErvzOxrv6H7VSpCdfSjNGAhrGR7dotaGkOS0w,5812
+flask_security/translations/ja_JP/LC_MESSAGES/flask_security.po,sha256=fAe0D_tJB92A1NIWChy-i01sr_OCkyitYXDdvVB58pA,31351
+flask_security/translations/nl_NL/LC_MESSAGES/flask_security.mo,sha256=CVTK54P6CSQsLUZPiKazCxzI7LhW4J2lqweA5Pwpkzw,6940
+flask_security/translations/nl_NL/LC_MESSAGES/flask_security.po,sha256=m-NxYHAdQ9b9amDbJj6BmNnrv6mFFMQI9Br9QvU09O4,32608
+flask_security/translations/pl_PL/LC_MESSAGES/flask_security.mo,sha256=rZTwDkNliT65lQ6WPPSTpSjQvzZFOGxUZE0iR4bgjy8,10843
+flask_security/translations/pl_PL/LC_MESSAGES/flask_security.po,sha256=laJCC9csqh1tGNaL49DUpNX6-8RXRlL8I2rPWlQi56M,34175
+flask_security/translations/pt_BR/LC_MESSAGES/flask_security.mo,sha256=9bcGc427y3HqcXIfmg5EMJSw7Ey1pCbiSBj_OAA1bXA,5313
+flask_security/translations/pt_BR/LC_MESSAGES/flask_security.po,sha256=m1egEpRrbPpFJ2HeNEjb0SL_7DW_ntKLMGsxFnkmgIE,30916
+flask_security/translations/pt_PT/LC_MESSAGES/flask_security.mo,sha256=1_Er5JTlz5IpOxlaXPxeC438t0i5mhPZ6-9Pehtw09U,5584
+flask_security/translations/pt_PT/LC_MESSAGES/flask_security.po,sha256=5VLqQA1wjeschmFFjp-5MwGgF-6sKfhO_No-xj2Rmw8,31210
+flask_security/translations/pwl.txt,sha256=DmseRpB-pKiulN5D2pGD9RcuQTtgAaV9VGgUkvfXdPs,40
+flask_security/translations/ru_RU/LC_MESSAGES/flask_security.mo,sha256=2kfiKfeQSvBXPnGe0mW6IKVBAjqnqjzFi6jG8ybZOpg,26102
+flask_security/translations/ru_RU/LC_MESSAGES/flask_security.po,sha256=NGLJQm9zFu5Vt9c8LCYv358E-fuMuupqDYMzJRolWn4,46025
+flask_security/translations/tr_TR/LC_MESSAGES/flask_security.mo,sha256=odP5xC0ItAlRA13Ixsjdt9fwR6cDHKc7tvRg8Yz1VL4,5386
+flask_security/translations/tr_TR/LC_MESSAGES/flask_security.po,sha256=-v2S6BTuTwnT2hP8cQfxSR0jAnpN311r99W-0VaOqkM,30969
+flask_security/translations/zh_Hans_CN/LC_MESSAGES/flask_security.mo,sha256=60Pk8evc0vCZKG6YIcb5uaa3r4ScVYNnHm_Zj-QL80E,8804
+flask_security/translations/zh_Hans_CN/LC_MESSAGES/flask_security.po,sha256=ECzTHWlXDf3UvxH3fORRI_9QBQV71tmaNUf7xE4bxSQ,32360
+flask_security/twofactor.py,sha256=Zg0YrjyVqDFPXDnqbL7ifsKxAQPGKkCJnytDJaCr908,8235
+flask_security/unified_signin.py,sha256=fb7ZIaUW7NfhwfjJEWs_OCaBAdZ7h5SbJh2XT1p4OpQ,38412
+flask_security/username_util.py,sha256=EjPliG4nUv5JAtLroAoTkZOzvlaISCFq2lA4g-EHd5A,3334
+flask_security/utils.py,sha256=W1AKBEO19zSMb2lxSk3ETvvr6Rz_2qUmy9Ljj1t6OCo,45789
+flask_security/views.py,sha256=q4rxVzr0GhGRJZKLJ9F9TpDsbHu1nbxCDbvtTTqZMH4,45877
+flask_security/webauthn.py,sha256=Aer1BCuClj2yoSUfk1FJh6UTD7obX7v9qEvrBSiiKfU,34602
+flask_security/webauthn_util.py,sha256=MW4G1CZT6jhv6Q3fPRUjEtsM2Yc4Uqk1pAs_SpWq_hk,6106
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..dc4e699002ca7b62117370dfbf518878b57aaba4
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_Security_Too-5.4.3.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_security
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f5c10ab28dd4921dd9d891f50dd95f721c66b13d
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Miguel Grinberg
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..ddec6b09ac16559597703be0cb3baad760ceb4dd
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/METADATA
@@ -0,0 +1,77 @@
+Metadata-Version: 2.1
+Name: Flask-SocketIO
+Version: 5.3.6
+Summary: Socket.IO integration for Flask applications
+Home-page: https://github.com/miguelgrinberg/flask-socketio
+Author: Miguel Grinberg
+Author-email: miguel.grinberg@gmail.com
+Project-URL: Bug Tracker, https://github.com/miguelgrinberg/flask-socketio/issues
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 3
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Requires-Python: >=3.6
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: Flask >=0.9
+Requires-Dist: python-socketio >=5.0.2
+Provides-Extra: docs
+Requires-Dist: sphinx ; extra == 'docs'
+
+Flask-SocketIO
+==============
+
+[](https://github.com/miguelgrinberg/Flask-SocketIO/actions) [](https://codecov.io/gh/miguelgrinberg/flask-socketio)
+
+Socket.IO integration for Flask applications.
+
+Sponsors
+--------
+
+The following organizations are funding this project:
+
+ [Socket.IO](https://socket.io) | [Add your company here!](https://github.com/sponsors/miguelgrinberg)|
+-|-
+
+Many individual sponsors also support this project through small ongoing contributions. Why not [join them](https://github.com/sponsors/miguelgrinberg)?
+
+Installation
+------------
+
+You can install this package as usual with pip:
+
+ pip install flask-socketio
+
+Example
+-------
+
+```py
+from flask import Flask, render_template
+from flask_socketio import SocketIO, emit
+
+app = Flask(__name__)
+app.config['SECRET_KEY'] = 'secret!'
+socketio = SocketIO(app)
+
+@app.route('/')
+def index():
+ return render_template('index.html')
+
+@socketio.event
+def my_event(message):
+ emit('my response', {'data': 'got it!'})
+
+if __name__ == '__main__':
+ socketio.run(app)
+```
+
+Resources
+---------
+
+- [Tutorial](http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent)
+- [Documentation](http://flask-socketio.readthedocs.io/en/latest/)
+- [PyPI](https://pypi.python.org/pypi/Flask-SocketIO)
+- [Change Log](https://github.com/miguelgrinberg/Flask-SocketIO/blob/main/CHANGES.md)
+- Questions? See the [questions](https://stackoverflow.com/questions/tagged/flask-socketio) others have asked on Stack Overflow, or [ask](https://stackoverflow.com/questions/ask?tags=python+flask-socketio+python-socketio) your own question.
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..92a5591b6e61e5f6229cf9e932a7744b9db949a3
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/RECORD
@@ -0,0 +1,13 @@
+Flask_SocketIO-5.3.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Flask_SocketIO-5.3.6.dist-info/LICENSE,sha256=aNCWbkgKjS_T1cJtACyZbvCM36KxWnfQ0LWTuavuYKQ,1082
+Flask_SocketIO-5.3.6.dist-info/METADATA,sha256=vmIOzjkNLXRjmocRXtso6hLV27aiJgH7_A55TVJyD4k,2631
+Flask_SocketIO-5.3.6.dist-info/RECORD,,
+Flask_SocketIO-5.3.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+Flask_SocketIO-5.3.6.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
+Flask_SocketIO-5.3.6.dist-info/top_level.txt,sha256=C1ugzQBJ3HHUJsWGzyt70XRVOX-y4CUAR8MWKjwJOQ8,15
+flask_socketio/__init__.py,sha256=ea3QXRYKBje4JQGcNSEOmj42qlf2peRNbCzZZWfD9DE,54731
+flask_socketio/__pycache__/__init__.cpython-311.pyc,,
+flask_socketio/__pycache__/namespace.cpython-311.pyc,,
+flask_socketio/__pycache__/test_client.cpython-311.pyc,,
+flask_socketio/namespace.py,sha256=b3oyXEemu2po-wpoy4ILTHQMVuVQqicogCDxfymfz_w,2020
+flask_socketio/test_client.py,sha256=9_R1y_vP8yr8wzimQUEMAUyVqX12FMXurLj8t1ecDdc,11034
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..7e688737d490be3643d705bc16b5a77f7bd567b7
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.41.2)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ba82ec385282c76890bfb754df00dec294a15eaa
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Flask_SocketIO-5.3.6.dist-info/top_level.txt
@@ -0,0 +1 @@
+flask_socketio
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..7cf3d43378af302e8dfaeed2f877c02b36d1882d
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/LICENSE
@@ -0,0 +1,19 @@
+Copyright 2006-2024 the Mako authors and contributors .
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..d9f1b094b66dd54b8b378cd071844a15ec6abca9
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/METADATA
@@ -0,0 +1,87 @@
+Metadata-Version: 2.1
+Name: Mako
+Version: 1.3.3
+Summary: A super-fast templating language that borrows the best ideas from the existing templating languages.
+Home-page: https://www.makotemplates.org/
+Author: Mike Bayer
+Author-email: mike@zzzcomputing.com
+License: MIT
+Project-URL: Documentation, https://docs.makotemplates.org
+Project-URL: Issue Tracker, https://github.com/sqlalchemy/mako
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: MarkupSafe >=0.9.2
+Provides-Extra: babel
+Requires-Dist: Babel ; extra == 'babel'
+Provides-Extra: lingua
+Requires-Dist: lingua ; extra == 'lingua'
+Provides-Extra: testing
+Requires-Dist: pytest ; extra == 'testing'
+
+=========================
+Mako Templates for Python
+=========================
+
+Mako is a template library written in Python. It provides a familiar, non-XML
+syntax which compiles into Python modules for maximum performance. Mako's
+syntax and API borrows from the best ideas of many others, including Django
+templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded
+Python (i.e. Python Server Page) language, which refines the familiar ideas
+of componentized layout and inheritance to produce one of the most
+straightforward and flexible models available, while also maintaining close
+ties to Python calling and scoping semantics.
+
+Nutshell
+========
+
+::
+
+ <%inherit file="base.html"/>
+ <%
+ rows = [[v for v in range(0,10)] for row in range(0,10)]
+ %>
+
+ % for row in rows:
+ ${makerow(row)}
+ % endfor
+
+
+ <%def name="makerow(row)">
+
+ % for name in row:
+
${name}
\
+ % endfor
+
+ %def>
+
+Philosophy
+===========
+
+Python is a great scripting language. Don't reinvent the wheel...your templates can handle it !
+
+Documentation
+==============
+
+See documentation for Mako at https://docs.makotemplates.org/en/latest/
+
+License
+========
+
+Mako is licensed under an MIT-style license (see LICENSE).
+Other incorporated projects may be licensed under different licenses.
+All licenses allow for non-commercial and commercial use.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..a0d86c23328944d8813918b8af4e8e14a491ac3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/RECORD
@@ -0,0 +1,74 @@
+../../Scripts/mako-render.exe,sha256=oBNZKcSgdhTPeG2lZPTjtrYzFhGXWBAdJAzhfQvbLcE,108459
+Mako-1.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+Mako-1.3.3.dist-info/LICENSE,sha256=FWJ7NrONBynN1obfmr9gZQPZnWJLL17FyyVKddWvqJE,1098
+Mako-1.3.3.dist-info/METADATA,sha256=_ZCe_t3T26oswKfiW8cu-rCMZJRVceys-qRkDs5dkYg,2900
+Mako-1.3.3.dist-info/RECORD,,
+Mako-1.3.3.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
+Mako-1.3.3.dist-info/entry_points.txt,sha256=LsKkUsOsJQYbJ2M72hZCm968wi5K8Ywb5uFxCuN8Obk,512
+Mako-1.3.3.dist-info/top_level.txt,sha256=LItdH8cDPetpUu8rUyBG3DObS6h9Gcpr9j_WLj2S-R0,5
+mako/__init__.py,sha256=REyVbMxZSkw8Mtn4M87228HathP20k18VD1xZ8svzHQ,242
+mako/__pycache__/__init__.cpython-311.pyc,,
+mako/__pycache__/_ast_util.cpython-311.pyc,,
+mako/__pycache__/ast.cpython-311.pyc,,
+mako/__pycache__/cache.cpython-311.pyc,,
+mako/__pycache__/cmd.cpython-311.pyc,,
+mako/__pycache__/codegen.cpython-311.pyc,,
+mako/__pycache__/compat.cpython-311.pyc,,
+mako/__pycache__/exceptions.cpython-311.pyc,,
+mako/__pycache__/filters.cpython-311.pyc,,
+mako/__pycache__/lexer.cpython-311.pyc,,
+mako/__pycache__/lookup.cpython-311.pyc,,
+mako/__pycache__/parsetree.cpython-311.pyc,,
+mako/__pycache__/pygen.cpython-311.pyc,,
+mako/__pycache__/pyparser.cpython-311.pyc,,
+mako/__pycache__/runtime.cpython-311.pyc,,
+mako/__pycache__/template.cpython-311.pyc,,
+mako/__pycache__/util.cpython-311.pyc,,
+mako/_ast_util.py,sha256=CenxCrdES1irHDhOQU6Ldta4rdsytfYaMkN6s0TlveM,20247
+mako/ast.py,sha256=pY7MH-5cLnUuVz5YAwoGhWgWfgoVvLQkRDtc_s9qqw0,6642
+mako/cache.py,sha256=5DBBorj1NqiWDqNhN3ZJ8tMCm-h6Mew541276kdsxAU,7680
+mako/cmd.py,sha256=vP5M5g9yc5sjAT5owVTQu056YwyS-YkpulFSDb0IMGw,2813
+mako/codegen.py,sha256=XRhzcuGEleDUXTfmOjw4alb6TkczbmEfBCLqID8x4bA,47736
+mako/compat.py,sha256=wjVMf7uMg0TlC_aI5hdwWizza99nqJuGNdrnTNrZbt0,1820
+mako/exceptions.py,sha256=pfdd5-1lCZ--I2YqQ_oHODZLmo62bn_lO5Kz_1__72w,12530
+mako/ext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+mako/ext/__pycache__/__init__.cpython-311.pyc,,
+mako/ext/__pycache__/autohandler.cpython-311.pyc,,
+mako/ext/__pycache__/babelplugin.cpython-311.pyc,,
+mako/ext/__pycache__/beaker_cache.cpython-311.pyc,,
+mako/ext/__pycache__/extract.cpython-311.pyc,,
+mako/ext/__pycache__/linguaplugin.cpython-311.pyc,,
+mako/ext/__pycache__/preprocessors.cpython-311.pyc,,
+mako/ext/__pycache__/pygmentplugin.cpython-311.pyc,,
+mako/ext/__pycache__/turbogears.cpython-311.pyc,,
+mako/ext/autohandler.py,sha256=Tyz1CLRlG_C0EnKgjuHzqS4BBnpeA49O05x8rriNtTY,1885
+mako/ext/babelplugin.py,sha256=v10o5XQdgXwbr1bo0aL8VV3THm_84C_eeq6BmAGd3uA,2091
+mako/ext/beaker_cache.py,sha256=aAs9ELzO2WaiO5OppV4KDT6f7yNyn1BF1XHDQZwf0-E,2578
+mako/ext/extract.py,sha256=c3YuIN3Z5ZgS-xzX_gjKrEVQaptK3liXkm5j-Vq8yEM,4659
+mako/ext/linguaplugin.py,sha256=pzHlHC3-KlFeVAR4r8S1--_dfE5DcYmjLXtr0genBYU,1935
+mako/ext/preprocessors.py,sha256=zKQy42Ce6dOmU0Yk_rUVDAAn38-RUUfQolVKTJjLotA,576
+mako/ext/pygmentplugin.py,sha256=qBdsAhKktlQX7d5Yv1sAXufUNOZqcnJmKuC7V4D_srM,4753
+mako/ext/turbogears.py,sha256=0emY1WiMnuY8Pf6ARv5JBArKtouUdmuTljI-w6rE3J4,2141
+mako/filters.py,sha256=F7aDIKTUxnT-Og4rgboQtnML7Q87DJTHQyhi_dY_Ih4,4658
+mako/lexer.py,sha256=dtCZU1eoF3ymEdiCwCzEIw5SH0lgJkDsHJy9VHI_2XY,16324
+mako/lookup.py,sha256=rkMvT5T7EOS5KRvPtgYii-sjh1nWWyKok_mEk-cEzrM,12428
+mako/parsetree.py,sha256=7RNVRTsKcsMt8vU4NQi5C7e4vhdUyA9tqyd1yIkvAAQ,19007
+mako/pygen.py,sha256=d4f_ugRACCXuV9hJgEk6Ncoj38EaRHA3RTxkr_tK7UQ,10416
+mako/pyparser.py,sha256=OdWhNznx2Z8IZRMpx6OocGd9EXqNOGgZTc-3lWWkLAE,7656
+mako/runtime.py,sha256=ZsUEN22nX3d3dECQujF69mBKDQS6yVv2nvz_0eTvFGg,27804
+mako/template.py,sha256=4xQzwruZd5XzPw7iONZMZJj4SdFsctYYg4PfBYs2PLk,23857
+mako/testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+mako/testing/__pycache__/__init__.cpython-311.pyc,,
+mako/testing/__pycache__/_config.cpython-311.pyc,,
+mako/testing/__pycache__/assertions.cpython-311.pyc,,
+mako/testing/__pycache__/config.cpython-311.pyc,,
+mako/testing/__pycache__/exclusions.cpython-311.pyc,,
+mako/testing/__pycache__/fixtures.cpython-311.pyc,,
+mako/testing/__pycache__/helpers.cpython-311.pyc,,
+mako/testing/_config.py,sha256=k-qpnsnbXUoN-ykMN5BRpg84i1x0p6UsAddKQnrIytU,3566
+mako/testing/assertions.py,sha256=pfbGl84QlW7QWGg3_lo3wP8XnBAVo9AjzNp2ajmn7FA,5161
+mako/testing/config.py,sha256=wmYVZfzGvOK3mJUZpzmgO8-iIgvaCH41Woi4yDpxq6E,323
+mako/testing/exclusions.py,sha256=_t6ADKdatk3f18tOfHV_ZY6u_ZwQsKphZ2MXJVSAOcI,1553
+mako/testing/fixtures.py,sha256=nEp7wTusf7E0n3Q-BHJW2s_t1vx0KB9poadQ1BmIJzE,3044
+mako/testing/helpers.py,sha256=z4HAactwlht4ut1cbvxKt1QLb3yLPk1U7cnh5BwVUlc,1623
+mako/util.py,sha256=dIFuchHfiNtRJJ99kEIRdHBkCZ3UmEvNO6l2ZQSCdVU,10638
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.43.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/entry_points.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..30f31b2bf217432c8a80e4a097268c7ffd79a986
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/entry_points.txt
@@ -0,0 +1,18 @@
+[babel.extractors]
+mako = mako.ext.babelplugin:extract [babel]
+
+[console_scripts]
+mako-render = mako.cmd:cmdline
+
+[lingua.extractors]
+mako = mako.ext.linguaplugin:LinguaMakoExtractor [lingua]
+
+[pygments.lexers]
+css+mako = mako.ext.pygmentplugin:MakoCssLexer
+html+mako = mako.ext.pygmentplugin:MakoHtmlLexer
+js+mako = mako.ext.pygmentplugin:MakoJavascriptLexer
+mako = mako.ext.pygmentplugin:MakoLexer
+xml+mako = mako.ext.pygmentplugin:MakoXmlLexer
+
+[python.templating.engines]
+mako = mako.ext.turbogears:TGPlugin
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2951cdd49d33f08a4f5af6213f315e571274c854
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/Mako-1.3.3.dist-info/top_level.txt
@@ -0,0 +1 @@
+mako
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/LICENSE.rst b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/LICENSE.rst
new file mode 100644
index 0000000000000000000000000000000000000000..c4700f975c9f76ccf9dec953157a92c549f450cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/LICENSE.rst
@@ -0,0 +1,28 @@
+Copyright 2010 Pallets
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..7354b5a5f91fbb92cf6a126745f51252bae9f0ce
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/METADATA
@@ -0,0 +1,93 @@
+Metadata-Version: 2.1
+Name: MarkupSafe
+Version: 2.1.5
+Summary: Safely add untrusted strings to HTML/XML markup.
+Home-page: https://palletsprojects.com/p/markupsafe/
+Maintainer: Pallets
+Maintainer-email: contact@palletsprojects.com
+License: BSD-3-Clause
+Project-URL: Donate, https://palletsprojects.com/donate
+Project-URL: Documentation, https://markupsafe.palletsprojects.com/
+Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
+Project-URL: Source Code, https://github.com/pallets/markupsafe/
+Project-URL: Issue Tracker, https://github.com/pallets/markupsafe/issues/
+Project-URL: Chat, https://discord.gg/pallets
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Text Processing :: Markup :: HTML
+Requires-Python: >=3.7
+Description-Content-Type: text/x-rst
+License-File: LICENSE.rst
+
+MarkupSafe
+==========
+
+MarkupSafe implements a text object that escapes characters so it is
+safe to use in HTML and XML. Characters that have special meanings are
+replaced so that they display as the actual characters. This mitigates
+injection attacks, meaning untrusted user input can safely be displayed
+on a page.
+
+
+Installing
+----------
+
+Install and update using `pip`_:
+
+.. code-block:: text
+
+ pip install -U MarkupSafe
+
+.. _pip: https://pip.pypa.io/en/stable/getting-started/
+
+
+Examples
+--------
+
+.. code-block:: pycon
+
+ >>> from markupsafe import Markup, escape
+
+ >>> # escape replaces special characters and wraps in Markup
+ >>> escape("")
+ Markup('<script>alert(document.cookie);</script>')
+
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
+ >>> Markup("Hello")
+ Markup('hello')
+
+ >>> escape(Markup("Hello"))
+ Markup('hello')
+
+ >>> # Markup is a str subclass
+ >>> # methods and operators escape their arguments
+ >>> template = Markup("Hello {name}")
+ >>> template.format(name='"World"')
+ Markup('Hello "World"')
+
+
+Donate
+------
+
+The Pallets organization develops and supports MarkupSafe and other
+popular packages. In order to grow the community of contributors and
+users, and allow the maintainers to devote more time to the projects,
+`please donate today`_.
+
+.. _please donate today: https://palletsprojects.com/donate
+
+
+Links
+-----
+
+- Documentation: https://markupsafe.palletsprojects.com/
+- Changes: https://markupsafe.palletsprojects.com/changes/
+- PyPI Releases: https://pypi.org/project/MarkupSafe/
+- Source Code: https://github.com/pallets/markupsafe/
+- Issue Tracker: https://github.com/pallets/markupsafe/issues/
+- Chat: https://discord.gg/pallets
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..82d4bda3b6c1c90b937f27e979e306c64fde46e9
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/RECORD
@@ -0,0 +1,14 @@
+MarkupSafe-2.1.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+MarkupSafe-2.1.5.dist-info/LICENSE.rst,sha256=RjHsDbX9kKVH4zaBcmTGeYIUM4FG-KyUtKV_lu6MnsQ,1503
+MarkupSafe-2.1.5.dist-info/METADATA,sha256=icNlaniV7YIQZ1BScCVqNaRtm7MAgfw8d3OBmoSVyAY,3096
+MarkupSafe-2.1.5.dist-info/RECORD,,
+MarkupSafe-2.1.5.dist-info/WHEEL,sha256=ircjsfhzblqgSzO8ow7-0pXK-RVqDqNRGQ8F650AUNM,102
+MarkupSafe-2.1.5.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11
+markupsafe/__init__.py,sha256=m1ysNeqf55zbEoJtaovca40ivrkEFolPlw5bGoC5Gi4,11290
+markupsafe/__pycache__/__init__.cpython-311.pyc,,
+markupsafe/__pycache__/_native.cpython-311.pyc,,
+markupsafe/_native.py,sha256=_Q7UsXCOvgdonCgqG3l5asANI6eo50EKnDM-mlwEC5M,1776
+markupsafe/_speedups.c,sha256=n3jzzaJwXcoN8nTFyA53f3vSqsWK2vujI-v6QYifjhQ,7403
+markupsafe/_speedups.cp311-win_amd64.pyd,sha256=MEqnkyBOHmstwQr50hKitovHjrHhMJ0gYmya4Fu1DK0,15872
+markupsafe/_speedups.pyi,sha256=f5QtwIOP0eLrxh2v5p6SmaYmlcHIGIfmz0DovaqL0OU,238
+markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d60b00472b6db035b28a0470c4bc8f72f5db2de0
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.42.0)
+Root-Is-Purelib: false
+Tag: cp311-cp311-win_amd64
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..75bf729258f9daef77370b6df1a57940f90fc23f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/MarkupSafe-2.1.5.dist-info/top_level.txt
@@ -0,0 +1 @@
+markupsafe
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/LICENSE.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c31ac56d772f7061c8b42f0ee96063b7a94a4859
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/LICENSE.txt
@@ -0,0 +1,284 @@
+A. HISTORY OF THE SOFTWARE
+==========================
+
+Python was created in the early 1990s by Guido van Rossum at Stichting
+Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
+as a successor of a language called ABC. Guido remains Python's
+principal author, although it includes many contributions from others.
+
+In 1995, Guido continued his work on Python at the Corporation for
+National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
+in Reston, Virginia where he released several versions of the
+software.
+
+In May 2000, Guido and the Python core development team moved to
+BeOpen.com to form the BeOpen PythonLabs team. In October of the same
+year, the PythonLabs team moved to Digital Creations (now Zope
+Corporation, see http://www.zope.com). In 2001, the Python Software
+Foundation (PSF, see http://www.python.org/psf/) was formed, a
+non-profit organization created specifically to own Python-related
+Intellectual Property. Zope Corporation is a sponsoring member of
+the PSF.
+
+All Python releases are Open Source (see http://www.opensource.org for
+the Open Source Definition). Historically, most, but not all, Python
+releases have also been GPL-compatible; the table below summarizes
+the various releases.
+
+ Release Derived Year Owner GPL-
+ from compatible? (1)
+
+ 0.9.0 thru 1.2 1991-1995 CWI yes
+ 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
+ 1.6 1.5.2 2000 CNRI no
+ 2.0 1.6 2000 BeOpen.com no
+ 1.6.1 1.6 2001 CNRI yes (2)
+ 2.1 2.0+1.6.1 2001 PSF no
+ 2.0.1 2.0+1.6.1 2001 PSF yes
+ 2.1.1 2.1+2.0.1 2001 PSF yes
+ 2.2 2.1.1 2001 PSF yes
+ 2.1.2 2.1.1 2002 PSF yes
+ 2.1.3 2.1.2 2002 PSF yes
+ 2.2.1 2.2 2002 PSF yes
+ 2.2.2 2.2.1 2002 PSF yes
+ 2.2.3 2.2.2 2003 PSF yes
+ 2.3 2.2.2 2002-2003 PSF yes
+ 2.3.1 2.3 2002-2003 PSF yes
+ 2.3.2 2.3.1 2002-2003 PSF yes
+ 2.3.3 2.3.2 2002-2003 PSF yes
+ 2.3.4 2.3.3 2004 PSF yes
+ 2.3.5 2.3.4 2005 PSF yes
+ 2.4 2.3 2004 PSF yes
+ 2.4.1 2.4 2005 PSF yes
+ 2.4.2 2.4.1 2005 PSF yes
+ 2.4.3 2.4.2 2006 PSF yes
+ 2.4.4 2.4.3 2006 PSF yes
+ 2.5 2.4 2006 PSF yes
+ 2.5.1 2.5 2007 PSF yes
+ 2.5.2 2.5.1 2008 PSF yes
+ 2.5.3 2.5.2 2008 PSF yes
+ 2.6 2.5 2008 PSF yes
+ 2.6.1 2.6 2008 PSF yes
+ 2.6.2 2.6.1 2009 PSF yes
+ 2.6.3 2.6.2 2009 PSF yes
+ 2.6.4 2.6.3 2009 PSF yes
+ 2.6.5 2.6.4 2010 PSF yes
+ 3.0 2.6 2008 PSF yes
+ 3.0.1 3.0 2009 PSF yes
+ 3.1 3.0.1 2009 PSF yes
+ 3.1.1 3.1 2009 PSF yes
+ 3.1.2 3.1 2010 PSF yes
+ 3.2 3.1 2010 PSF yes
+
+Footnotes:
+
+(1) GPL-compatible doesn't mean that we're distributing Python under
+ the GPL. All Python licenses, unlike the GPL, let you distribute
+ a modified version without making your changes open source. The
+ GPL-compatible licenses make it possible to combine Python with
+ other software that is released under the GPL; the others don't.
+
+(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
+ because its license has a choice of law clause. According to
+ CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
+ is "not incompatible" with the GPL.
+
+Thanks to the many outside volunteers who have worked under Guido's
+direction to make these releases possible.
+
+
+B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
+===============================================================
+
+PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
+--------------------------------------------
+
+1. This LICENSE AGREEMENT is between the Python Software Foundation
+("PSF"), and the Individual or Organization ("Licensee") accessing and
+otherwise using this software ("Python") in source or binary form and
+its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, PSF hereby
+grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+analyze, test, perform and/or display publicly, prepare derivative works,
+distribute, and otherwise use Python alone or in any derivative version,
+provided, however, that PSF's License Agreement and PSF's notice of copyright,
+i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
+Python Software Foundation; All Rights Reserved" are retained in Python alone or
+in any derivative version prepared by Licensee.
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python.
+
+4. PSF is making Python available to Licensee on an "AS IS"
+basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. Nothing in this License Agreement shall be deemed to create any
+relationship of agency, partnership, or joint venture between PSF and
+Licensee. This License Agreement does not grant permission to use PSF
+trademarks or trade name in a trademark sense to endorse or promote
+products or services of Licensee, or any third party.
+
+8. By copying, installing or otherwise using Python, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
+-------------------------------------------
+
+BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
+
+1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
+office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
+Individual or Organization ("Licensee") accessing and otherwise using
+this software in source or binary form and its associated
+documentation ("the Software").
+
+2. Subject to the terms and conditions of this BeOpen Python License
+Agreement, BeOpen hereby grants Licensee a non-exclusive,
+royalty-free, world-wide license to reproduce, analyze, test, perform
+and/or display publicly, prepare derivative works, distribute, and
+otherwise use the Software alone or in any derivative version,
+provided, however, that the BeOpen Python License is retained in the
+Software, alone or in any derivative version prepared by Licensee.
+
+3. BeOpen is making the Software available to Licensee on an "AS IS"
+basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
+SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
+AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
+DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+5. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+6. This License Agreement shall be governed by and interpreted in all
+respects by the law of the State of California, excluding conflict of
+law provisions. Nothing in this License Agreement shall be deemed to
+create any relationship of agency, partnership, or joint venture
+between BeOpen and Licensee. This License Agreement does not grant
+permission to use BeOpen trademarks or trade names in a trademark
+sense to endorse or promote products or services of Licensee, or any
+third party. As an exception, the "BeOpen Python" logos available at
+http://www.pythonlabs.com/logos.html may be used according to the
+permissions granted on that web page.
+
+7. By copying, installing or otherwise using the software, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
+---------------------------------------
+
+1. This LICENSE AGREEMENT is between the Corporation for National
+Research Initiatives, having an office at 1895 Preston White Drive,
+Reston, VA 20191 ("CNRI"), and the Individual or Organization
+("Licensee") accessing and otherwise using Python 1.6.1 software in
+source or binary form and its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, CNRI
+hereby grants Licensee a nonexclusive, royalty-free, world-wide
+license to reproduce, analyze, test, perform and/or display publicly,
+prepare derivative works, distribute, and otherwise use Python 1.6.1
+alone or in any derivative version, provided, however, that CNRI's
+License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
+1995-2001 Corporation for National Research Initiatives; All Rights
+Reserved" are retained in Python 1.6.1 alone or in any derivative
+version prepared by Licensee. Alternately, in lieu of CNRI's License
+Agreement, Licensee may substitute the following text (omitting the
+quotes): "Python 1.6.1 is made available subject to the terms and
+conditions in CNRI's License Agreement. This Agreement together with
+Python 1.6.1 may be located on the Internet using the following
+unique, persistent identifier (known as a handle): 1895.22/1013. This
+Agreement may also be obtained from a proxy server on the Internet
+using the following URL: http://hdl.handle.net/1895.22/1013".
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python 1.6.1 or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python 1.6.1.
+
+4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
+basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. This License Agreement shall be governed by the federal
+intellectual property law of the United States, including without
+limitation the federal copyright law, and, to the extent such
+U.S. federal law does not apply, by the law of the Commonwealth of
+Virginia, excluding Virginia's conflict of law provisions.
+Notwithstanding the foregoing, with regard to derivative works based
+on Python 1.6.1 that incorporate non-separable material that was
+previously distributed under the GNU General Public License (GPL), the
+law of the Commonwealth of Virginia shall govern this License
+Agreement only as to issues arising under or with respect to
+Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
+License Agreement shall be deemed to create any relationship of
+agency, partnership, or joint venture between CNRI and Licensee. This
+License Agreement does not grant permission to use CNRI trademarks or
+trade name in a trademark sense to endorse or promote products or
+services of Licensee, or any third party.
+
+8. By clicking on the "ACCEPT" button where indicated, or by copying,
+installing or otherwise using Python 1.6.1, Licensee agrees to be
+bound by the terms and conditions of this License Agreement.
+
+ ACCEPT
+
+
+CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
+--------------------------------------------------
+
+Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
+The Netherlands. All rights reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation, and that the name of Stichting Mathematisch
+Centrum or CWI not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
+FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..3ef03ead00c7a30a5a1e666f8a6e2d027587eea9
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/METADATA
@@ -0,0 +1,116 @@
+Metadata-Version: 2.1
+Name: distlib
+Version: 0.3.8
+Summary: Distribution utilities
+Home-page: https://github.com/pypa/distlib
+Author: Vinay Sajip
+Author-email: vinay_sajip@red-dove.com
+License: PSF-2.0
+Project-URL: Documentation, https://distlib.readthedocs.io/
+Project-URL: Source, https://github.com/pypa/distlib
+Project-URL: Tracker, https://github.com/pypa/distlib/issues
+Platform: any
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Python Software Foundation License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Topic :: Software Development
+License-File: LICENSE.txt
+
+|badge1| |badge2|
+
+.. |badge1| image:: https://img.shields.io/github/actions/workflow/status/pypa/distlib/package-tests.yml
+ :alt: GitHub Workflow Status (with event)
+
+.. |badge2| image:: https://img.shields.io/codecov/c/github/pypa/distlib
+ :target: https://app.codecov.io/gh/pypa/distlib
+ :alt: GitHub coverage status
+
+What is it?
+-----------
+
+Distlib is a library which implements low-level functions that relate to
+packaging and distribution of Python software. It is intended to be used as the
+basis for third-party packaging tools. The documentation is available at
+
+https://distlib.readthedocs.io/
+
+Main features
+-------------
+
+Distlib currently offers the following features:
+
+* The package ``distlib.database``, which implements a database of installed
+ distributions, as defined by :pep:`376`, and distribution dependency graph
+ logic. Support is also provided for non-installed distributions (i.e.
+ distributions registered with metadata on an index like PyPI), including
+ the ability to scan for dependencies and building dependency graphs.
+* The package ``distlib.index``, which implements an interface to perform
+ operations on an index, such as registering a project, uploading a
+ distribution or uploading documentation. Support is included for verifying
+ SSL connections (with domain matching) and signing/verifying packages using
+ GnuPG.
+* The package ``distlib.metadata``, which implements distribution metadata as
+ defined by :pep:`643`, :pep:`566`, :pep:`345`, :pep:`314` and :pep:`241`.
+* The package ``distlib.markers``, which implements environment markers as
+ defined by :pep:`508`.
+* The package ``distlib.manifest``, which implements lists of files used
+ in packaging source distributions.
+* The package ``distlib.locators``, which allows finding distributions, whether
+ on PyPI (XML-RPC or via the "simple" interface), local directories or some
+ other source.
+* The package ``distlib.resources``, which allows access to data files stored
+ in Python packages, both in the file system and in .zip files.
+* The package ``distlib.scripts``, which allows installing of scripts with
+ adjustment of shebang lines and support for native Windows executable
+ launchers.
+* The package ``distlib.version``, which implements version specifiers as
+ defined by :pep:`440`, but also support for working with "legacy" versions and
+ semantic versions.
+* The package ``distlib.wheel``, which provides support for building and
+ installing from the Wheel format for binary distributions (see :pep:`427`).
+* The package ``distlib.util``, which contains miscellaneous functions and
+ classes which are useful in packaging, but which do not fit neatly into
+ one of the other packages in ``distlib``.* The package implements enhanced
+ globbing functionality such as the ability to use ``**`` in patterns to
+ specify recursing into subdirectories.
+
+
+Python version and platform compatibility
+-----------------------------------------
+
+Distlib is intended to be used on and is tested on Python versions 2.7 and 3.6 or later,
+pypy-2.7 and pypy3 on Linux, Windows, and macOS.
+
+Project status
+--------------
+
+The project has reached a mature status in its development: there is a comprehensive
+test suite and it has been exercised on Windows, Ubuntu and macOS. The project is used
+by well-known projects such as `pip `_ and `caniusepython3
+`_.
+
+This project was migrated from Mercurial to Git and from BitBucket to GitHub, and
+although all information of importance has been retained across the migration, some
+commit references in issues and issue comments may have become invalid.
+
+Code of Conduct
+---------------
+
+Everyone interacting in the distlib project's codebases, issue trackers, chat
+rooms, and mailing lists is expected to follow the `PyPA Code of Conduct`_.
+
+.. _PyPA Code of Conduct: https://www.pypa.io/en/latest/code-of-conduct/
+
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..2c256188798b31c7191d57c0405c2160e9b4b073
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/RECORD
@@ -0,0 +1,38 @@
+distlib-0.3.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+distlib-0.3.8.dist-info/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531
+distlib-0.3.8.dist-info/METADATA,sha256=fZ0RSmI_JQ3hbH5cq8kN-cnwqfRQiL0gc3imV5RZXqY,5144
+distlib-0.3.8.dist-info/RECORD,,
+distlib-0.3.8.dist-info/WHEEL,sha256=z9j0xAa_JmUKMpmz72K0ZGALSM_n-wQVmGbleXx2VHg,110
+distlib-0.3.8.dist-info/top_level.txt,sha256=9BERqitu_vzyeyILOcGzX9YyA2AB_xlC4-81V6xoizk,8
+distlib/__init__.py,sha256=hJKF7FHoqbmGckncDuEINWo_OYkDNiHODtYXSMcvjcc,625
+distlib/__pycache__/__init__.cpython-311.pyc,,
+distlib/__pycache__/compat.cpython-311.pyc,,
+distlib/__pycache__/database.cpython-311.pyc,,
+distlib/__pycache__/index.cpython-311.pyc,,
+distlib/__pycache__/locators.cpython-311.pyc,,
+distlib/__pycache__/manifest.cpython-311.pyc,,
+distlib/__pycache__/markers.cpython-311.pyc,,
+distlib/__pycache__/metadata.cpython-311.pyc,,
+distlib/__pycache__/resources.cpython-311.pyc,,
+distlib/__pycache__/scripts.cpython-311.pyc,,
+distlib/__pycache__/util.cpython-311.pyc,,
+distlib/__pycache__/version.cpython-311.pyc,,
+distlib/__pycache__/wheel.cpython-311.pyc,,
+distlib/compat.py,sha256=Un-uIBvy02w-D267OG4VEhuddqWgKj9nNkxVltAb75w,41487
+distlib/database.py,sha256=0V9Qvs0Vrxa2F_-hLWitIyVyRifJ0pCxyOI-kEOBwsA,51965
+distlib/index.py,sha256=lTbw268rRhj8dw1sib3VZ_0EhSGgoJO3FKJzSFMOaeA,20797
+distlib/locators.py,sha256=o1r_M86_bRLafSpetmyfX8KRtFu-_Q58abvQrnOSnbA,51767
+distlib/manifest.py,sha256=3qfmAmVwxRqU1o23AlfXrQGZzh6g_GGzTAP_Hb9C5zQ,14168
+distlib/markers.py,sha256=n3DfOh1yvZ_8EW7atMyoYeZFXjYla0Nz0itQlojCd0A,5268
+distlib/metadata.py,sha256=pB9WZ9mBfmQxc9OVIldLS5CjOoQRvKAvUwwQyKwKQtQ,39693
+distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820
+distlib/scripts.py,sha256=nQFXN6G7nOWNDUyxirUep-3WOlJhB7McvCs9zOnkGTI,18315
+distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792
+distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784
+distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032
+distlib/util.py,sha256=XSznxEi_i3T20UJuaVc0qXHz5ksGUCW1khYlBprN_QE,67530
+distlib/version.py,sha256=9pXkduchve_aN7JG6iL9VTYV_kqNSGoc2Dwl8JuySnQ,23747
+distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648
+distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448
+distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888
+distlib/wheel.py,sha256=FVQCve8u-L0QYk5-YTZc7s4WmNQdvjRWTK08KXzZVX4,43958
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..0b18a281107a0448a9980396d9d324ea2aa7a7f8
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.37.1)
+Root-Is-Purelib: true
+Tag: py2-none-any
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f68bb07272ddc517a1ca4c3d4e50ac67bf78d3e2
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib-0.3.8.dist-info/top_level.txt
@@ -0,0 +1 @@
+distlib
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e999438fe94a0cc507a89dd1824cbd879db72cd9
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/__init__.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2012-2023 Vinay Sajip.
+# Licensed to the Python Software Foundation under a contributor agreement.
+# See LICENSE.txt and CONTRIBUTORS.txt.
+#
+import logging
+
+__version__ = '0.3.8'
+
+
+class DistlibException(Exception):
+ pass
+
+
+try:
+ from logging import NullHandler
+except ImportError: # pragma: no cover
+
+ class NullHandler(logging.Handler):
+
+ def handle(self, record):
+ pass
+
+ def emit(self, record):
+ pass
+
+ def createLock(self):
+ self.lock = None
+
+
+logger = logging.getLogger(__name__)
+logger.addHandler(NullHandler())
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/t32.exe b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/t32.exe
new file mode 100644
index 0000000000000000000000000000000000000000..52154f0be32cc2bdbf98af131d477900667d0abd
Binary files /dev/null and b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/t32.exe differ
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba58858d0fb21f8d0d30089ebadfbd9833f07e57
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/util.py
@@ -0,0 +1,2025 @@
+#
+# Copyright (C) 2012-2023 The Python Software Foundation.
+# See LICENSE.txt and CONTRIBUTORS.txt.
+#
+import codecs
+from collections import deque
+import contextlib
+import csv
+from glob import iglob as std_iglob
+import io
+import json
+import logging
+import os
+import py_compile
+import re
+import socket
+try:
+ import ssl
+except ImportError: # pragma: no cover
+ ssl = None
+import subprocess
+import sys
+import tarfile
+import tempfile
+import textwrap
+
+try:
+ import threading
+except ImportError: # pragma: no cover
+ import dummy_threading as threading
+import time
+
+from . import DistlibException
+from .compat import (string_types, text_type, shutil, raw_input, StringIO,
+ cache_from_source, urlopen, urljoin, httplib, xmlrpclib,
+ HTTPHandler, BaseConfigurator, valid_ident,
+ Container, configparser, URLError, ZipFile, fsdecode,
+ unquote, urlparse)
+
+logger = logging.getLogger(__name__)
+
+#
+# Requirement parsing code as per PEP 508
+#
+
+IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')
+VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')
+COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')
+MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')
+OR = re.compile(r'^or\b\s*')
+AND = re.compile(r'^and\b\s*')
+NON_SPACE = re.compile(r'(\S+)\s*')
+STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')
+
+
+def parse_marker(marker_string):
+ """
+ Parse a marker string and return a dictionary containing a marker expression.
+
+ The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
+ the expression grammar, or strings. A string contained in quotes is to be
+ interpreted as a literal string, and a string not contained in quotes is a
+ variable (such as os_name).
+ """
+
+ def marker_var(remaining):
+ # either identifier, or literal string
+ m = IDENTIFIER.match(remaining)
+ if m:
+ result = m.groups()[0]
+ remaining = remaining[m.end():]
+ elif not remaining:
+ raise SyntaxError('unexpected end of input')
+ else:
+ q = remaining[0]
+ if q not in '\'"':
+ raise SyntaxError('invalid expression: %s' % remaining)
+ oq = '\'"'.replace(q, '')
+ remaining = remaining[1:]
+ parts = [q]
+ while remaining:
+ # either a string chunk, or oq, or q to terminate
+ if remaining[0] == q:
+ break
+ elif remaining[0] == oq:
+ parts.append(oq)
+ remaining = remaining[1:]
+ else:
+ m = STRING_CHUNK.match(remaining)
+ if not m:
+ raise SyntaxError('error in string literal: %s' %
+ remaining)
+ parts.append(m.groups()[0])
+ remaining = remaining[m.end():]
+ else:
+ s = ''.join(parts)
+ raise SyntaxError('unterminated string: %s' % s)
+ parts.append(q)
+ result = ''.join(parts)
+ remaining = remaining[1:].lstrip() # skip past closing quote
+ return result, remaining
+
+ def marker_expr(remaining):
+ if remaining and remaining[0] == '(':
+ result, remaining = marker(remaining[1:].lstrip())
+ if remaining[0] != ')':
+ raise SyntaxError('unterminated parenthesis: %s' % remaining)
+ remaining = remaining[1:].lstrip()
+ else:
+ lhs, remaining = marker_var(remaining)
+ while remaining:
+ m = MARKER_OP.match(remaining)
+ if not m:
+ break
+ op = m.groups()[0]
+ remaining = remaining[m.end():]
+ rhs, remaining = marker_var(remaining)
+ lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
+ result = lhs
+ return result, remaining
+
+ def marker_and(remaining):
+ lhs, remaining = marker_expr(remaining)
+ while remaining:
+ m = AND.match(remaining)
+ if not m:
+ break
+ remaining = remaining[m.end():]
+ rhs, remaining = marker_expr(remaining)
+ lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
+ return lhs, remaining
+
+ def marker(remaining):
+ lhs, remaining = marker_and(remaining)
+ while remaining:
+ m = OR.match(remaining)
+ if not m:
+ break
+ remaining = remaining[m.end():]
+ rhs, remaining = marker_and(remaining)
+ lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
+ return lhs, remaining
+
+ return marker(marker_string)
+
+
+def parse_requirement(req):
+ """
+ Parse a requirement passed in as a string. Return a Container
+ whose attributes contain the various parts of the requirement.
+ """
+ remaining = req.strip()
+ if not remaining or remaining.startswith('#'):
+ return None
+ m = IDENTIFIER.match(remaining)
+ if not m:
+ raise SyntaxError('name expected: %s' % remaining)
+ distname = m.groups()[0]
+ remaining = remaining[m.end():]
+ extras = mark_expr = versions = uri = None
+ if remaining and remaining[0] == '[':
+ i = remaining.find(']', 1)
+ if i < 0:
+ raise SyntaxError('unterminated extra: %s' % remaining)
+ s = remaining[1:i]
+ remaining = remaining[i + 1:].lstrip()
+ extras = []
+ while s:
+ m = IDENTIFIER.match(s)
+ if not m:
+ raise SyntaxError('malformed extra: %s' % s)
+ extras.append(m.groups()[0])
+ s = s[m.end():]
+ if not s:
+ break
+ if s[0] != ',':
+ raise SyntaxError('comma expected in extras: %s' % s)
+ s = s[1:].lstrip()
+ if not extras:
+ extras = None
+ if remaining:
+ if remaining[0] == '@':
+ # it's a URI
+ remaining = remaining[1:].lstrip()
+ m = NON_SPACE.match(remaining)
+ if not m:
+ raise SyntaxError('invalid URI: %s' % remaining)
+ uri = m.groups()[0]
+ t = urlparse(uri)
+ # there are issues with Python and URL parsing, so this test
+ # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
+ # always parse invalid URLs correctly - it should raise
+ # exceptions for malformed URLs
+ if not (t.scheme and t.netloc):
+ raise SyntaxError('Invalid URL: %s' % uri)
+ remaining = remaining[m.end():].lstrip()
+ else:
+
+ def get_versions(ver_remaining):
+ """
+ Return a list of operator, version tuples if any are
+ specified, else None.
+ """
+ m = COMPARE_OP.match(ver_remaining)
+ versions = None
+ if m:
+ versions = []
+ while True:
+ op = m.groups()[0]
+ ver_remaining = ver_remaining[m.end():]
+ m = VERSION_IDENTIFIER.match(ver_remaining)
+ if not m:
+ raise SyntaxError('invalid version: %s' %
+ ver_remaining)
+ v = m.groups()[0]
+ versions.append((op, v))
+ ver_remaining = ver_remaining[m.end():]
+ if not ver_remaining or ver_remaining[0] != ',':
+ break
+ ver_remaining = ver_remaining[1:].lstrip()
+ # Some packages have a trailing comma which would break things
+ # See issue #148
+ if not ver_remaining:
+ break
+ m = COMPARE_OP.match(ver_remaining)
+ if not m:
+ raise SyntaxError('invalid constraint: %s' %
+ ver_remaining)
+ if not versions:
+ versions = None
+ return versions, ver_remaining
+
+ if remaining[0] != '(':
+ versions, remaining = get_versions(remaining)
+ else:
+ i = remaining.find(')', 1)
+ if i < 0:
+ raise SyntaxError('unterminated parenthesis: %s' %
+ remaining)
+ s = remaining[1:i]
+ remaining = remaining[i + 1:].lstrip()
+ # As a special diversion from PEP 508, allow a version number
+ # a.b.c in parentheses as a synonym for ~= a.b.c (because this
+ # is allowed in earlier PEPs)
+ if COMPARE_OP.match(s):
+ versions, _ = get_versions(s)
+ else:
+ m = VERSION_IDENTIFIER.match(s)
+ if not m:
+ raise SyntaxError('invalid constraint: %s' % s)
+ v = m.groups()[0]
+ s = s[m.end():].lstrip()
+ if s:
+ raise SyntaxError('invalid constraint: %s' % s)
+ versions = [('~=', v)]
+
+ if remaining:
+ if remaining[0] != ';':
+ raise SyntaxError('invalid requirement: %s' % remaining)
+ remaining = remaining[1:].lstrip()
+
+ mark_expr, remaining = parse_marker(remaining)
+
+ if remaining and remaining[0] != '#':
+ raise SyntaxError('unexpected trailing data: %s' % remaining)
+
+ if not versions:
+ rs = distname
+ else:
+ rs = '%s %s' % (distname, ', '.join(
+ ['%s %s' % con for con in versions]))
+ return Container(name=distname,
+ extras=extras,
+ constraints=versions,
+ marker=mark_expr,
+ url=uri,
+ requirement=rs)
+
+
+def get_resources_dests(resources_root, rules):
+ """Find destinations for resources files"""
+
+ def get_rel_path(root, path):
+ # normalizes and returns a lstripped-/-separated path
+ root = root.replace(os.path.sep, '/')
+ path = path.replace(os.path.sep, '/')
+ assert path.startswith(root)
+ return path[len(root):].lstrip('/')
+
+ destinations = {}
+ for base, suffix, dest in rules:
+ prefix = os.path.join(resources_root, base)
+ for abs_base in iglob(prefix):
+ abs_glob = os.path.join(abs_base, suffix)
+ for abs_path in iglob(abs_glob):
+ resource_file = get_rel_path(resources_root, abs_path)
+ if dest is None: # remove the entry if it was here
+ destinations.pop(resource_file, None)
+ else:
+ rel_path = get_rel_path(abs_base, abs_path)
+ rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
+ destinations[resource_file] = rel_dest + '/' + rel_path
+ return destinations
+
+
+def in_venv():
+ if hasattr(sys, 'real_prefix'):
+ # virtualenv venvs
+ result = True
+ else:
+ # PEP 405 venvs
+ result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
+ return result
+
+
+def get_executable():
+ # The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as
+ # changes to the stub launcher mean that sys.executable always points
+ # to the stub on OS X
+ # if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
+ # in os.environ):
+ # result = os.environ['__PYVENV_LAUNCHER__']
+ # else:
+ # result = sys.executable
+ # return result
+ # Avoid normcasing: see issue #143
+ # result = os.path.normcase(sys.executable)
+ result = sys.executable
+ if not isinstance(result, text_type):
+ result = fsdecode(result)
+ return result
+
+
+def proceed(prompt, allowed_chars, error_prompt=None, default=None):
+ p = prompt
+ while True:
+ s = raw_input(p)
+ p = prompt
+ if not s and default:
+ s = default
+ if s:
+ c = s[0].lower()
+ if c in allowed_chars:
+ break
+ if error_prompt:
+ p = '%c: %s\n%s' % (c, error_prompt, prompt)
+ return c
+
+
+def extract_by_key(d, keys):
+ if isinstance(keys, string_types):
+ keys = keys.split()
+ result = {}
+ for key in keys:
+ if key in d:
+ result[key] = d[key]
+ return result
+
+
+def read_exports(stream):
+ if sys.version_info[0] >= 3:
+ # needs to be a text stream
+ stream = codecs.getreader('utf-8')(stream)
+ # Try to load as JSON, falling back on legacy format
+ data = stream.read()
+ stream = StringIO(data)
+ try:
+ jdata = json.load(stream)
+ result = jdata['extensions']['python.exports']['exports']
+ for group, entries in result.items():
+ for k, v in entries.items():
+ s = '%s = %s' % (k, v)
+ entry = get_export_entry(s)
+ assert entry is not None
+ entries[k] = entry
+ return result
+ except Exception:
+ stream.seek(0, 0)
+
+ def read_stream(cp, stream):
+ if hasattr(cp, 'read_file'):
+ cp.read_file(stream)
+ else:
+ cp.readfp(stream)
+
+ cp = configparser.ConfigParser()
+ try:
+ read_stream(cp, stream)
+ except configparser.MissingSectionHeaderError:
+ stream.close()
+ data = textwrap.dedent(data)
+ stream = StringIO(data)
+ read_stream(cp, stream)
+
+ result = {}
+ for key in cp.sections():
+ result[key] = entries = {}
+ for name, value in cp.items(key):
+ s = '%s = %s' % (name, value)
+ entry = get_export_entry(s)
+ assert entry is not None
+ # entry.dist = self
+ entries[name] = entry
+ return result
+
+
+def write_exports(exports, stream):
+ if sys.version_info[0] >= 3:
+ # needs to be a text stream
+ stream = codecs.getwriter('utf-8')(stream)
+ cp = configparser.ConfigParser()
+ for k, v in exports.items():
+ # TODO check k, v for valid values
+ cp.add_section(k)
+ for entry in v.values():
+ if entry.suffix is None:
+ s = entry.prefix
+ else:
+ s = '%s:%s' % (entry.prefix, entry.suffix)
+ if entry.flags:
+ s = '%s [%s]' % (s, ', '.join(entry.flags))
+ cp.set(k, entry.name, s)
+ cp.write(stream)
+
+
+@contextlib.contextmanager
+def tempdir():
+ td = tempfile.mkdtemp()
+ try:
+ yield td
+ finally:
+ shutil.rmtree(td)
+
+
+@contextlib.contextmanager
+def chdir(d):
+ cwd = os.getcwd()
+ try:
+ os.chdir(d)
+ yield
+ finally:
+ os.chdir(cwd)
+
+
+@contextlib.contextmanager
+def socket_timeout(seconds=15):
+ cto = socket.getdefaulttimeout()
+ try:
+ socket.setdefaulttimeout(seconds)
+ yield
+ finally:
+ socket.setdefaulttimeout(cto)
+
+
+class cached_property(object):
+
+ def __init__(self, func):
+ self.func = func
+ # for attr in ('__name__', '__module__', '__doc__'):
+ # setattr(self, attr, getattr(func, attr, None))
+
+ def __get__(self, obj, cls=None):
+ if obj is None:
+ return self
+ value = self.func(obj)
+ object.__setattr__(obj, self.func.__name__, value)
+ # obj.__dict__[self.func.__name__] = value = self.func(obj)
+ return value
+
+
+def convert_path(pathname):
+ """Return 'pathname' as a name that will work on the native filesystem.
+
+ The path is split on '/' and put back together again using the current
+ directory separator. Needed because filenames in the setup script are
+ always supplied in Unix style, and have to be converted to the local
+ convention before we can actually use them in the filesystem. Raises
+ ValueError on non-Unix-ish systems if 'pathname' either starts or
+ ends with a slash.
+ """
+ if os.sep == '/':
+ return pathname
+ if not pathname:
+ return pathname
+ if pathname[0] == '/':
+ raise ValueError("path '%s' cannot be absolute" % pathname)
+ if pathname[-1] == '/':
+ raise ValueError("path '%s' cannot end with '/'" % pathname)
+
+ paths = pathname.split('/')
+ while os.curdir in paths:
+ paths.remove(os.curdir)
+ if not paths:
+ return os.curdir
+ return os.path.join(*paths)
+
+
+class FileOperator(object):
+
+ def __init__(self, dry_run=False):
+ self.dry_run = dry_run
+ self.ensured = set()
+ self._init_record()
+
+ def _init_record(self):
+ self.record = False
+ self.files_written = set()
+ self.dirs_created = set()
+
+ def record_as_written(self, path):
+ if self.record:
+ self.files_written.add(path)
+
+ def newer(self, source, target):
+ """Tell if the target is newer than the source.
+
+ Returns true if 'source' exists and is more recently modified than
+ 'target', or if 'source' exists and 'target' doesn't.
+
+ Returns false if both exist and 'target' is the same age or younger
+ than 'source'. Raise PackagingFileError if 'source' does not exist.
+
+ Note that this test is not very accurate: files created in the same
+ second will have the same "age".
+ """
+ if not os.path.exists(source):
+ raise DistlibException("file '%r' does not exist" %
+ os.path.abspath(source))
+ if not os.path.exists(target):
+ return True
+
+ return os.stat(source).st_mtime > os.stat(target).st_mtime
+
+ def copy_file(self, infile, outfile, check=True):
+ """Copy a file respecting dry-run and force flags.
+ """
+ self.ensure_dir(os.path.dirname(outfile))
+ logger.info('Copying %s to %s', infile, outfile)
+ if not self.dry_run:
+ msg = None
+ if check:
+ if os.path.islink(outfile):
+ msg = '%s is a symlink' % outfile
+ elif os.path.exists(outfile) and not os.path.isfile(outfile):
+ msg = '%s is a non-regular file' % outfile
+ if msg:
+ raise ValueError(msg + ' which would be overwritten')
+ shutil.copyfile(infile, outfile)
+ self.record_as_written(outfile)
+
+ def copy_stream(self, instream, outfile, encoding=None):
+ assert not os.path.isdir(outfile)
+ self.ensure_dir(os.path.dirname(outfile))
+ logger.info('Copying stream %s to %s', instream, outfile)
+ if not self.dry_run:
+ if encoding is None:
+ outstream = open(outfile, 'wb')
+ else:
+ outstream = codecs.open(outfile, 'w', encoding=encoding)
+ try:
+ shutil.copyfileobj(instream, outstream)
+ finally:
+ outstream.close()
+ self.record_as_written(outfile)
+
+ def write_binary_file(self, path, data):
+ self.ensure_dir(os.path.dirname(path))
+ if not self.dry_run:
+ if os.path.exists(path):
+ os.remove(path)
+ with open(path, 'wb') as f:
+ f.write(data)
+ self.record_as_written(path)
+
+ def write_text_file(self, path, data, encoding):
+ self.write_binary_file(path, data.encode(encoding))
+
+ def set_mode(self, bits, mask, files):
+ if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):
+ # Set the executable bits (owner, group, and world) on
+ # all the files specified.
+ for f in files:
+ if self.dry_run:
+ logger.info("changing mode of %s", f)
+ else:
+ mode = (os.stat(f).st_mode | bits) & mask
+ logger.info("changing mode of %s to %o", f, mode)
+ os.chmod(f, mode)
+
+ set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)
+
+ def ensure_dir(self, path):
+ path = os.path.abspath(path)
+ if path not in self.ensured and not os.path.exists(path):
+ self.ensured.add(path)
+ d, f = os.path.split(path)
+ self.ensure_dir(d)
+ logger.info('Creating %s' % path)
+ if not self.dry_run:
+ os.mkdir(path)
+ if self.record:
+ self.dirs_created.add(path)
+
+ def byte_compile(self,
+ path,
+ optimize=False,
+ force=False,
+ prefix=None,
+ hashed_invalidation=False):
+ dpath = cache_from_source(path, not optimize)
+ logger.info('Byte-compiling %s to %s', path, dpath)
+ if not self.dry_run:
+ if force or self.newer(path, dpath):
+ if not prefix:
+ diagpath = None
+ else:
+ assert path.startswith(prefix)
+ diagpath = path[len(prefix):]
+ compile_kwargs = {}
+ if hashed_invalidation and hasattr(py_compile,
+ 'PycInvalidationMode'):
+ compile_kwargs[
+ 'invalidation_mode'] = py_compile.PycInvalidationMode.CHECKED_HASH
+ py_compile.compile(path, dpath, diagpath, True,
+ **compile_kwargs) # raise error
+ self.record_as_written(dpath)
+ return dpath
+
+ def ensure_removed(self, path):
+ if os.path.exists(path):
+ if os.path.isdir(path) and not os.path.islink(path):
+ logger.debug('Removing directory tree at %s', path)
+ if not self.dry_run:
+ shutil.rmtree(path)
+ if self.record:
+ if path in self.dirs_created:
+ self.dirs_created.remove(path)
+ else:
+ if os.path.islink(path):
+ s = 'link'
+ else:
+ s = 'file'
+ logger.debug('Removing %s %s', s, path)
+ if not self.dry_run:
+ os.remove(path)
+ if self.record:
+ if path in self.files_written:
+ self.files_written.remove(path)
+
+ def is_writable(self, path):
+ result = False
+ while not result:
+ if os.path.exists(path):
+ result = os.access(path, os.W_OK)
+ break
+ parent = os.path.dirname(path)
+ if parent == path:
+ break
+ path = parent
+ return result
+
+ def commit(self):
+ """
+ Commit recorded changes, turn off recording, return
+ changes.
+ """
+ assert self.record
+ result = self.files_written, self.dirs_created
+ self._init_record()
+ return result
+
+ def rollback(self):
+ if not self.dry_run:
+ for f in list(self.files_written):
+ if os.path.exists(f):
+ os.remove(f)
+ # dirs should all be empty now, except perhaps for
+ # __pycache__ subdirs
+ # reverse so that subdirs appear before their parents
+ dirs = sorted(self.dirs_created, reverse=True)
+ for d in dirs:
+ flist = os.listdir(d)
+ if flist:
+ assert flist == ['__pycache__']
+ sd = os.path.join(d, flist[0])
+ os.rmdir(sd)
+ os.rmdir(d) # should fail if non-empty
+ self._init_record()
+
+
+def resolve(module_name, dotted_path):
+ if module_name in sys.modules:
+ mod = sys.modules[module_name]
+ else:
+ mod = __import__(module_name)
+ if dotted_path is None:
+ result = mod
+ else:
+ parts = dotted_path.split('.')
+ result = getattr(mod, parts.pop(0))
+ for p in parts:
+ result = getattr(result, p)
+ return result
+
+
+class ExportEntry(object):
+
+ def __init__(self, name, prefix, suffix, flags):
+ self.name = name
+ self.prefix = prefix
+ self.suffix = suffix
+ self.flags = flags
+
+ @cached_property
+ def value(self):
+ return resolve(self.prefix, self.suffix)
+
+ def __repr__(self): # pragma: no cover
+ return '' % (self.name, self.prefix,
+ self.suffix, self.flags)
+
+ def __eq__(self, other):
+ if not isinstance(other, ExportEntry):
+ result = False
+ else:
+ result = (self.name == other.name and self.prefix == other.prefix
+ and self.suffix == other.suffix
+ and self.flags == other.flags)
+ return result
+
+ __hash__ = object.__hash__
+
+
+ENTRY_RE = re.compile(
+ r'''(?P([^\[]\S*))
+ \s*=\s*(?P(\w+)([:\.]\w+)*)
+ \s*(\[\s*(?P[\w-]+(=\w+)?(,\s*\w+(=\w+)?)*)\s*\])?
+ ''', re.VERBOSE)
+
+
+def get_export_entry(specification):
+ m = ENTRY_RE.search(specification)
+ if not m:
+ result = None
+ if '[' in specification or ']' in specification:
+ raise DistlibException("Invalid specification "
+ "'%s'" % specification)
+ else:
+ d = m.groupdict()
+ name = d['name']
+ path = d['callable']
+ colons = path.count(':')
+ if colons == 0:
+ prefix, suffix = path, None
+ else:
+ if colons != 1:
+ raise DistlibException("Invalid specification "
+ "'%s'" % specification)
+ prefix, suffix = path.split(':')
+ flags = d['flags']
+ if flags is None:
+ if '[' in specification or ']' in specification:
+ raise DistlibException("Invalid specification "
+ "'%s'" % specification)
+ flags = []
+ else:
+ flags = [f.strip() for f in flags.split(',')]
+ result = ExportEntry(name, prefix, suffix, flags)
+ return result
+
+
+def get_cache_base(suffix=None):
+ """
+ Return the default base location for distlib caches. If the directory does
+ not exist, it is created. Use the suffix provided for the base directory,
+ and default to '.distlib' if it isn't provided.
+
+ On Windows, if LOCALAPPDATA is defined in the environment, then it is
+ assumed to be a directory, and will be the parent directory of the result.
+ On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
+ directory - using os.expanduser('~') - will be the parent directory of
+ the result.
+
+ The result is just the directory '.distlib' in the parent directory as
+ determined above, or with the name specified with ``suffix``.
+ """
+ if suffix is None:
+ suffix = '.distlib'
+ if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
+ result = os.path.expandvars('$localappdata')
+ else:
+ # Assume posix, or old Windows
+ result = os.path.expanduser('~')
+ # we use 'isdir' instead of 'exists', because we want to
+ # fail if there's a file with that name
+ if os.path.isdir(result):
+ usable = os.access(result, os.W_OK)
+ if not usable:
+ logger.warning('Directory exists but is not writable: %s', result)
+ else:
+ try:
+ os.makedirs(result)
+ usable = True
+ except OSError:
+ logger.warning('Unable to create %s', result, exc_info=True)
+ usable = False
+ if not usable:
+ result = tempfile.mkdtemp()
+ logger.warning('Default location unusable, using %s', result)
+ return os.path.join(result, suffix)
+
+
+def path_to_cache_dir(path):
+ """
+ Convert an absolute path to a directory name for use in a cache.
+
+ The algorithm used is:
+
+ #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
+ #. Any occurrence of ``os.sep`` is replaced with ``'--'``.
+ #. ``'.cache'`` is appended.
+ """
+ d, p = os.path.splitdrive(os.path.abspath(path))
+ if d:
+ d = d.replace(':', '---')
+ p = p.replace(os.sep, '--')
+ return d + p + '.cache'
+
+
+def ensure_slash(s):
+ if not s.endswith('/'):
+ return s + '/'
+ return s
+
+
+def parse_credentials(netloc):
+ username = password = None
+ if '@' in netloc:
+ prefix, netloc = netloc.rsplit('@', 1)
+ if ':' not in prefix:
+ username = prefix
+ else:
+ username, password = prefix.split(':', 1)
+ if username:
+ username = unquote(username)
+ if password:
+ password = unquote(password)
+ return username, password, netloc
+
+
+def get_process_umask():
+ result = os.umask(0o22)
+ os.umask(result)
+ return result
+
+
+def is_string_sequence(seq):
+ result = True
+ i = None
+ for i, s in enumerate(seq):
+ if not isinstance(s, string_types):
+ result = False
+ break
+ assert i is not None
+ return result
+
+
+PROJECT_NAME_AND_VERSION = re.compile(
+ '([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'
+ '([a-z0-9_.+-]+)', re.I)
+PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')
+
+
+def split_filename(filename, project_name=None):
+ """
+ Extract name, version, python version from a filename (no extension)
+
+ Return name, version, pyver or None
+ """
+ result = None
+ pyver = None
+ filename = unquote(filename).replace(' ', '-')
+ m = PYTHON_VERSION.search(filename)
+ if m:
+ pyver = m.group(1)
+ filename = filename[:m.start()]
+ if project_name and len(filename) > len(project_name) + 1:
+ m = re.match(re.escape(project_name) + r'\b', filename)
+ if m:
+ n = m.end()
+ result = filename[:n], filename[n + 1:], pyver
+ if result is None:
+ m = PROJECT_NAME_AND_VERSION.match(filename)
+ if m:
+ result = m.group(1), m.group(3), pyver
+ return result
+
+
+# Allow spaces in name because of legacy dists like "Twisted Core"
+NAME_VERSION_RE = re.compile(r'(?P[\w .-]+)\s*'
+ r'\(\s*(?P[^\s)]+)\)$')
+
+
+def parse_name_and_version(p):
+ """
+ A utility method used to get name and version from a string.
+
+ From e.g. a Provides-Dist value.
+
+ :param p: A value in a form 'foo (1.0)'
+ :return: The name and version as a tuple.
+ """
+ m = NAME_VERSION_RE.match(p)
+ if not m:
+ raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
+ d = m.groupdict()
+ return d['name'].strip().lower(), d['ver']
+
+
+def get_extras(requested, available):
+ result = set()
+ requested = set(requested or [])
+ available = set(available or [])
+ if '*' in requested:
+ requested.remove('*')
+ result |= available
+ for r in requested:
+ if r == '-':
+ result.add(r)
+ elif r.startswith('-'):
+ unwanted = r[1:]
+ if unwanted not in available:
+ logger.warning('undeclared extra: %s' % unwanted)
+ if unwanted in result:
+ result.remove(unwanted)
+ else:
+ if r not in available:
+ logger.warning('undeclared extra: %s' % r)
+ result.add(r)
+ return result
+
+
+#
+# Extended metadata functionality
+#
+
+
+def _get_external_data(url):
+ result = {}
+ try:
+ # urlopen might fail if it runs into redirections,
+ # because of Python issue #13696. Fixed in locators
+ # using a custom redirect handler.
+ resp = urlopen(url)
+ headers = resp.info()
+ ct = headers.get('Content-Type')
+ if not ct.startswith('application/json'):
+ logger.debug('Unexpected response for JSON request: %s', ct)
+ else:
+ reader = codecs.getreader('utf-8')(resp)
+ # data = reader.read().decode('utf-8')
+ # result = json.loads(data)
+ result = json.load(reader)
+ except Exception as e:
+ logger.exception('Failed to get external data for %s: %s', url, e)
+ return result
+
+
+_external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
+
+
+def get_project_data(name):
+ url = '%s/%s/project.json' % (name[0].upper(), name)
+ url = urljoin(_external_data_base_url, url)
+ result = _get_external_data(url)
+ return result
+
+
+def get_package_data(name, version):
+ url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)
+ url = urljoin(_external_data_base_url, url)
+ return _get_external_data(url)
+
+
+class Cache(object):
+ """
+ A class implementing a cache for resources that need to live in the file system
+ e.g. shared libraries. This class was moved from resources to here because it
+ could be used by other modules, e.g. the wheel module.
+ """
+
+ def __init__(self, base):
+ """
+ Initialise an instance.
+
+ :param base: The base directory where the cache should be located.
+ """
+ # we use 'isdir' instead of 'exists', because we want to
+ # fail if there's a file with that name
+ if not os.path.isdir(base): # pragma: no cover
+ os.makedirs(base)
+ if (os.stat(base).st_mode & 0o77) != 0:
+ logger.warning('Directory \'%s\' is not private', base)
+ self.base = os.path.abspath(os.path.normpath(base))
+
+ def prefix_to_dir(self, prefix):
+ """
+ Converts a resource prefix to a directory name in the cache.
+ """
+ return path_to_cache_dir(prefix)
+
+ def clear(self):
+ """
+ Clear the cache.
+ """
+ not_removed = []
+ for fn in os.listdir(self.base):
+ fn = os.path.join(self.base, fn)
+ try:
+ if os.path.islink(fn) or os.path.isfile(fn):
+ os.remove(fn)
+ elif os.path.isdir(fn):
+ shutil.rmtree(fn)
+ except Exception:
+ not_removed.append(fn)
+ return not_removed
+
+
+class EventMixin(object):
+ """
+ A very simple publish/subscribe system.
+ """
+
+ def __init__(self):
+ self._subscribers = {}
+
+ def add(self, event, subscriber, append=True):
+ """
+ Add a subscriber for an event.
+
+ :param event: The name of an event.
+ :param subscriber: The subscriber to be added (and called when the
+ event is published).
+ :param append: Whether to append or prepend the subscriber to an
+ existing subscriber list for the event.
+ """
+ subs = self._subscribers
+ if event not in subs:
+ subs[event] = deque([subscriber])
+ else:
+ sq = subs[event]
+ if append:
+ sq.append(subscriber)
+ else:
+ sq.appendleft(subscriber)
+
+ def remove(self, event, subscriber):
+ """
+ Remove a subscriber for an event.
+
+ :param event: The name of an event.
+ :param subscriber: The subscriber to be removed.
+ """
+ subs = self._subscribers
+ if event not in subs:
+ raise ValueError('No subscribers: %r' % event)
+ subs[event].remove(subscriber)
+
+ def get_subscribers(self, event):
+ """
+ Return an iterator for the subscribers for an event.
+ :param event: The event to return subscribers for.
+ """
+ return iter(self._subscribers.get(event, ()))
+
+ def publish(self, event, *args, **kwargs):
+ """
+ Publish a event and return a list of values returned by its
+ subscribers.
+
+ :param event: The event to publish.
+ :param args: The positional arguments to pass to the event's
+ subscribers.
+ :param kwargs: The keyword arguments to pass to the event's
+ subscribers.
+ """
+ result = []
+ for subscriber in self.get_subscribers(event):
+ try:
+ value = subscriber(event, *args, **kwargs)
+ except Exception:
+ logger.exception('Exception during event publication')
+ value = None
+ result.append(value)
+ logger.debug('publish %s: args = %s, kwargs = %s, result = %s', event,
+ args, kwargs, result)
+ return result
+
+
+#
+# Simple sequencing
+#
+class Sequencer(object):
+
+ def __init__(self):
+ self._preds = {}
+ self._succs = {}
+ self._nodes = set() # nodes with no preds/succs
+
+ def add_node(self, node):
+ self._nodes.add(node)
+
+ def remove_node(self, node, edges=False):
+ if node in self._nodes:
+ self._nodes.remove(node)
+ if edges:
+ for p in set(self._preds.get(node, ())):
+ self.remove(p, node)
+ for s in set(self._succs.get(node, ())):
+ self.remove(node, s)
+ # Remove empties
+ for k, v in list(self._preds.items()):
+ if not v:
+ del self._preds[k]
+ for k, v in list(self._succs.items()):
+ if not v:
+ del self._succs[k]
+
+ def add(self, pred, succ):
+ assert pred != succ
+ self._preds.setdefault(succ, set()).add(pred)
+ self._succs.setdefault(pred, set()).add(succ)
+
+ def remove(self, pred, succ):
+ assert pred != succ
+ try:
+ preds = self._preds[succ]
+ succs = self._succs[pred]
+ except KeyError: # pragma: no cover
+ raise ValueError('%r not a successor of anything' % succ)
+ try:
+ preds.remove(pred)
+ succs.remove(succ)
+ except KeyError: # pragma: no cover
+ raise ValueError('%r not a successor of %r' % (succ, pred))
+
+ def is_step(self, step):
+ return (step in self._preds or step in self._succs
+ or step in self._nodes)
+
+ def get_steps(self, final):
+ if not self.is_step(final):
+ raise ValueError('Unknown: %r' % final)
+ result = []
+ todo = []
+ seen = set()
+ todo.append(final)
+ while todo:
+ step = todo.pop(0)
+ if step in seen:
+ # if a step was already seen,
+ # move it to the end (so it will appear earlier
+ # when reversed on return) ... but not for the
+ # final step, as that would be confusing for
+ # users
+ if step != final:
+ result.remove(step)
+ result.append(step)
+ else:
+ seen.add(step)
+ result.append(step)
+ preds = self._preds.get(step, ())
+ todo.extend(preds)
+ return reversed(result)
+
+ @property
+ def strong_connections(self):
+ # http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
+ index_counter = [0]
+ stack = []
+ lowlinks = {}
+ index = {}
+ result = []
+
+ graph = self._succs
+
+ def strongconnect(node):
+ # set the depth index for this node to the smallest unused index
+ index[node] = index_counter[0]
+ lowlinks[node] = index_counter[0]
+ index_counter[0] += 1
+ stack.append(node)
+
+ # Consider successors
+ try:
+ successors = graph[node]
+ except Exception:
+ successors = []
+ for successor in successors:
+ if successor not in lowlinks:
+ # Successor has not yet been visited
+ strongconnect(successor)
+ lowlinks[node] = min(lowlinks[node], lowlinks[successor])
+ elif successor in stack:
+ # the successor is in the stack and hence in the current
+ # strongly connected component (SCC)
+ lowlinks[node] = min(lowlinks[node], index[successor])
+
+ # If `node` is a root node, pop the stack and generate an SCC
+ if lowlinks[node] == index[node]:
+ connected_component = []
+
+ while True:
+ successor = stack.pop()
+ connected_component.append(successor)
+ if successor == node:
+ break
+ component = tuple(connected_component)
+ # storing the result
+ result.append(component)
+
+ for node in graph:
+ if node not in lowlinks:
+ strongconnect(node)
+
+ return result
+
+ @property
+ def dot(self):
+ result = ['digraph G {']
+ for succ in self._preds:
+ preds = self._preds[succ]
+ for pred in preds:
+ result.append(' %s -> %s;' % (pred, succ))
+ for node in self._nodes:
+ result.append(' %s;' % node)
+ result.append('}')
+ return '\n'.join(result)
+
+
+#
+# Unarchiving functionality for zip, tar, tgz, tbz, whl
+#
+
+ARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz',
+ '.whl')
+
+
+def unarchive(archive_filename, dest_dir, format=None, check=True):
+
+ def check_path(path):
+ if not isinstance(path, text_type):
+ path = path.decode('utf-8')
+ p = os.path.abspath(os.path.join(dest_dir, path))
+ if not p.startswith(dest_dir) or p[plen] != os.sep:
+ raise ValueError('path outside destination: %r' % p)
+
+ dest_dir = os.path.abspath(dest_dir)
+ plen = len(dest_dir)
+ archive = None
+ if format is None:
+ if archive_filename.endswith(('.zip', '.whl')):
+ format = 'zip'
+ elif archive_filename.endswith(('.tar.gz', '.tgz')):
+ format = 'tgz'
+ mode = 'r:gz'
+ elif archive_filename.endswith(('.tar.bz2', '.tbz')):
+ format = 'tbz'
+ mode = 'r:bz2'
+ elif archive_filename.endswith('.tar'):
+ format = 'tar'
+ mode = 'r'
+ else: # pragma: no cover
+ raise ValueError('Unknown format for %r' % archive_filename)
+ try:
+ if format == 'zip':
+ archive = ZipFile(archive_filename, 'r')
+ if check:
+ names = archive.namelist()
+ for name in names:
+ check_path(name)
+ else:
+ archive = tarfile.open(archive_filename, mode)
+ if check:
+ names = archive.getnames()
+ for name in names:
+ check_path(name)
+ if format != 'zip' and sys.version_info[0] < 3:
+ # See Python issue 17153. If the dest path contains Unicode,
+ # tarfile extraction fails on Python 2.x if a member path name
+ # contains non-ASCII characters - it leads to an implicit
+ # bytes -> unicode conversion using ASCII to decode.
+ for tarinfo in archive.getmembers():
+ if not isinstance(tarinfo.name, text_type):
+ tarinfo.name = tarinfo.name.decode('utf-8')
+
+ # Limit extraction of dangerous items, if this Python
+ # allows it easily. If not, just trust the input.
+ # See: https://docs.python.org/3/library/tarfile.html#extraction-filters
+ def extraction_filter(member, path):
+ """Run tarfile.tar_filter, but raise the expected ValueError"""
+ # This is only called if the current Python has tarfile filters
+ try:
+ return tarfile.tar_filter(member, path)
+ except tarfile.FilterError as exc:
+ raise ValueError(str(exc))
+
+ archive.extraction_filter = extraction_filter
+
+ archive.extractall(dest_dir)
+
+ finally:
+ if archive:
+ archive.close()
+
+
+def zip_dir(directory):
+ """zip a directory tree into a BytesIO object"""
+ result = io.BytesIO()
+ dlen = len(directory)
+ with ZipFile(result, "w") as zf:
+ for root, dirs, files in os.walk(directory):
+ for name in files:
+ full = os.path.join(root, name)
+ rel = root[dlen:]
+ dest = os.path.join(rel, name)
+ zf.write(full, dest)
+ return result
+
+
+#
+# Simple progress bar
+#
+
+UNITS = ('', 'K', 'M', 'G', 'T', 'P')
+
+
+class Progress(object):
+ unknown = 'UNKNOWN'
+
+ def __init__(self, minval=0, maxval=100):
+ assert maxval is None or maxval >= minval
+ self.min = self.cur = minval
+ self.max = maxval
+ self.started = None
+ self.elapsed = 0
+ self.done = False
+
+ def update(self, curval):
+ assert self.min <= curval
+ assert self.max is None or curval <= self.max
+ self.cur = curval
+ now = time.time()
+ if self.started is None:
+ self.started = now
+ else:
+ self.elapsed = now - self.started
+
+ def increment(self, incr):
+ assert incr >= 0
+ self.update(self.cur + incr)
+
+ def start(self):
+ self.update(self.min)
+ return self
+
+ def stop(self):
+ if self.max is not None:
+ self.update(self.max)
+ self.done = True
+
+ @property
+ def maximum(self):
+ return self.unknown if self.max is None else self.max
+
+ @property
+ def percentage(self):
+ if self.done:
+ result = '100 %'
+ elif self.max is None:
+ result = ' ?? %'
+ else:
+ v = 100.0 * (self.cur - self.min) / (self.max - self.min)
+ result = '%3d %%' % v
+ return result
+
+ def format_duration(self, duration):
+ if (duration <= 0) and self.max is None or self.cur == self.min:
+ result = '??:??:??'
+ # elif duration < 1:
+ # result = '--:--:--'
+ else:
+ result = time.strftime('%H:%M:%S', time.gmtime(duration))
+ return result
+
+ @property
+ def ETA(self):
+ if self.done:
+ prefix = 'Done'
+ t = self.elapsed
+ # import pdb; pdb.set_trace()
+ else:
+ prefix = 'ETA '
+ if self.max is None:
+ t = -1
+ elif self.elapsed == 0 or (self.cur == self.min):
+ t = 0
+ else:
+ # import pdb; pdb.set_trace()
+ t = float(self.max - self.min)
+ t /= self.cur - self.min
+ t = (t - 1) * self.elapsed
+ return '%s: %s' % (prefix, self.format_duration(t))
+
+ @property
+ def speed(self):
+ if self.elapsed == 0:
+ result = 0.0
+ else:
+ result = (self.cur - self.min) / self.elapsed
+ for unit in UNITS:
+ if result < 1000:
+ break
+ result /= 1000.0
+ return '%d %sB/s' % (result, unit)
+
+
+#
+# Glob functionality
+#
+
+RICH_GLOB = re.compile(r'\{([^}]*)\}')
+_CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
+_CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
+
+
+def iglob(path_glob):
+ """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
+ if _CHECK_RECURSIVE_GLOB.search(path_glob):
+ msg = """invalid glob %r: recursive glob "**" must be used alone"""
+ raise ValueError(msg % path_glob)
+ if _CHECK_MISMATCH_SET.search(path_glob):
+ msg = """invalid glob %r: mismatching set marker '{' or '}'"""
+ raise ValueError(msg % path_glob)
+ return _iglob(path_glob)
+
+
+def _iglob(path_glob):
+ rich_path_glob = RICH_GLOB.split(path_glob, 1)
+ if len(rich_path_glob) > 1:
+ assert len(rich_path_glob) == 3, rich_path_glob
+ prefix, set, suffix = rich_path_glob
+ for item in set.split(','):
+ for path in _iglob(''.join((prefix, item, suffix))):
+ yield path
+ else:
+ if '**' not in path_glob:
+ for item in std_iglob(path_glob):
+ yield item
+ else:
+ prefix, radical = path_glob.split('**', 1)
+ if prefix == '':
+ prefix = '.'
+ if radical == '':
+ radical = '*'
+ else:
+ # we support both
+ radical = radical.lstrip('/')
+ radical = radical.lstrip('\\')
+ for path, dir, files in os.walk(prefix):
+ path = os.path.normpath(path)
+ for fn in _iglob(os.path.join(path, radical)):
+ yield fn
+
+
+if ssl:
+ from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname,
+ CertificateError)
+
+ #
+ # HTTPSConnection which verifies certificates/matches domains
+ #
+
+ class HTTPSConnection(httplib.HTTPSConnection):
+ ca_certs = None # set this to the path to the certs file (.pem)
+ check_domain = True # only used if ca_certs is not None
+
+ # noinspection PyPropertyAccess
+ def connect(self):
+ sock = socket.create_connection((self.host, self.port),
+ self.timeout)
+ if getattr(self, '_tunnel_host', False):
+ self.sock = sock
+ self._tunnel()
+
+ context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+ if hasattr(ssl, 'OP_NO_SSLv2'):
+ context.options |= ssl.OP_NO_SSLv2
+ if getattr(self, 'cert_file', None):
+ context.load_cert_chain(self.cert_file, self.key_file)
+ kwargs = {}
+ if self.ca_certs:
+ context.verify_mode = ssl.CERT_REQUIRED
+ context.load_verify_locations(cafile=self.ca_certs)
+ if getattr(ssl, 'HAS_SNI', False):
+ kwargs['server_hostname'] = self.host
+
+ self.sock = context.wrap_socket(sock, **kwargs)
+ if self.ca_certs and self.check_domain:
+ try:
+ match_hostname(self.sock.getpeercert(), self.host)
+ logger.debug('Host verified: %s', self.host)
+ except CertificateError: # pragma: no cover
+ self.sock.shutdown(socket.SHUT_RDWR)
+ self.sock.close()
+ raise
+
+ class HTTPSHandler(BaseHTTPSHandler):
+
+ def __init__(self, ca_certs, check_domain=True):
+ BaseHTTPSHandler.__init__(self)
+ self.ca_certs = ca_certs
+ self.check_domain = check_domain
+
+ def _conn_maker(self, *args, **kwargs):
+ """
+ This is called to create a connection instance. Normally you'd
+ pass a connection class to do_open, but it doesn't actually check for
+ a class, and just expects a callable. As long as we behave just as a
+ constructor would have, we should be OK. If it ever changes so that
+ we *must* pass a class, we'll create an UnsafeHTTPSConnection class
+ which just sets check_domain to False in the class definition, and
+ choose which one to pass to do_open.
+ """
+ result = HTTPSConnection(*args, **kwargs)
+ if self.ca_certs:
+ result.ca_certs = self.ca_certs
+ result.check_domain = self.check_domain
+ return result
+
+ def https_open(self, req):
+ try:
+ return self.do_open(self._conn_maker, req)
+ except URLError as e:
+ if 'certificate verify failed' in str(e.reason):
+ raise CertificateError(
+ 'Unable to verify server certificate '
+ 'for %s' % req.host)
+ else:
+ raise
+
+ #
+ # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-
+ # Middle proxy using HTTP listens on port 443, or an index mistakenly serves
+ # HTML containing a http://xyz link when it should be https://xyz),
+ # you can use the following handler class, which does not allow HTTP traffic.
+ #
+ # It works by inheriting from HTTPHandler - so build_opener won't add a
+ # handler for HTTP itself.
+ #
+ class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):
+
+ def http_open(self, req):
+ raise URLError(
+ 'Unexpected HTTP request on what should be a secure '
+ 'connection: %s' % req)
+
+
+#
+# XML-RPC with timeouts
+#
+class Transport(xmlrpclib.Transport):
+
+ def __init__(self, timeout, use_datetime=0):
+ self.timeout = timeout
+ xmlrpclib.Transport.__init__(self, use_datetime)
+
+ def make_connection(self, host):
+ h, eh, x509 = self.get_host_info(host)
+ if not self._connection or host != self._connection[0]:
+ self._extra_headers = eh
+ self._connection = host, httplib.HTTPConnection(h)
+ return self._connection[1]
+
+
+if ssl:
+
+ class SafeTransport(xmlrpclib.SafeTransport):
+
+ def __init__(self, timeout, use_datetime=0):
+ self.timeout = timeout
+ xmlrpclib.SafeTransport.__init__(self, use_datetime)
+
+ def make_connection(self, host):
+ h, eh, kwargs = self.get_host_info(host)
+ if not kwargs:
+ kwargs = {}
+ kwargs['timeout'] = self.timeout
+ if not self._connection or host != self._connection[0]:
+ self._extra_headers = eh
+ self._connection = host, httplib.HTTPSConnection(
+ h, None, **kwargs)
+ return self._connection[1]
+
+
+class ServerProxy(xmlrpclib.ServerProxy):
+
+ def __init__(self, uri, **kwargs):
+ self.timeout = timeout = kwargs.pop('timeout', None)
+ # The above classes only come into play if a timeout
+ # is specified
+ if timeout is not None:
+ # scheme = splittype(uri) # deprecated as of Python 3.8
+ scheme = urlparse(uri)[0]
+ use_datetime = kwargs.get('use_datetime', 0)
+ if scheme == 'https':
+ tcls = SafeTransport
+ else:
+ tcls = Transport
+ kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)
+ self.transport = t
+ xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)
+
+
+#
+# CSV functionality. This is provided because on 2.x, the csv module can't
+# handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.
+#
+
+
+def _csv_open(fn, mode, **kwargs):
+ if sys.version_info[0] < 3:
+ mode += 'b'
+ else:
+ kwargs['newline'] = ''
+ # Python 3 determines encoding from locale. Force 'utf-8'
+ # file encoding to match other forced utf-8 encoding
+ kwargs['encoding'] = 'utf-8'
+ return open(fn, mode, **kwargs)
+
+
+class CSVBase(object):
+ defaults = {
+ 'delimiter': str(','), # The strs are used because we need native
+ 'quotechar': str('"'), # str in the csv API (2.x won't take
+ 'lineterminator': str('\n') # Unicode)
+ }
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc_info):
+ self.stream.close()
+
+
+class CSVReader(CSVBase):
+
+ def __init__(self, **kwargs):
+ if 'stream' in kwargs:
+ stream = kwargs['stream']
+ if sys.version_info[0] >= 3:
+ # needs to be a text stream
+ stream = codecs.getreader('utf-8')(stream)
+ self.stream = stream
+ else:
+ self.stream = _csv_open(kwargs['path'], 'r')
+ self.reader = csv.reader(self.stream, **self.defaults)
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ result = next(self.reader)
+ if sys.version_info[0] < 3:
+ for i, item in enumerate(result):
+ if not isinstance(item, text_type):
+ result[i] = item.decode('utf-8')
+ return result
+
+ __next__ = next
+
+
+class CSVWriter(CSVBase):
+
+ def __init__(self, fn, **kwargs):
+ self.stream = _csv_open(fn, 'w')
+ self.writer = csv.writer(self.stream, **self.defaults)
+
+ def writerow(self, row):
+ if sys.version_info[0] < 3:
+ r = []
+ for item in row:
+ if isinstance(item, text_type):
+ item = item.encode('utf-8')
+ r.append(item)
+ row = r
+ self.writer.writerow(row)
+
+
+#
+# Configurator functionality
+#
+
+
+class Configurator(BaseConfigurator):
+
+ value_converters = dict(BaseConfigurator.value_converters)
+ value_converters['inc'] = 'inc_convert'
+
+ def __init__(self, config, base=None):
+ super(Configurator, self).__init__(config)
+ self.base = base or os.getcwd()
+
+ def configure_custom(self, config):
+
+ def convert(o):
+ if isinstance(o, (list, tuple)):
+ result = type(o)([convert(i) for i in o])
+ elif isinstance(o, dict):
+ if '()' in o:
+ result = self.configure_custom(o)
+ else:
+ result = {}
+ for k in o:
+ result[k] = convert(o[k])
+ else:
+ result = self.convert(o)
+ return result
+
+ c = config.pop('()')
+ if not callable(c):
+ c = self.resolve(c)
+ props = config.pop('.', None)
+ # Check for valid identifiers
+ args = config.pop('[]', ())
+ if args:
+ args = tuple([convert(o) for o in args])
+ items = [(k, convert(config[k])) for k in config if valid_ident(k)]
+ kwargs = dict(items)
+ result = c(*args, **kwargs)
+ if props:
+ for n, v in props.items():
+ setattr(result, n, convert(v))
+ return result
+
+ def __getitem__(self, key):
+ result = self.config[key]
+ if isinstance(result, dict) and '()' in result:
+ self.config[key] = result = self.configure_custom(result)
+ return result
+
+ def inc_convert(self, value):
+ """Default converter for the inc:// protocol."""
+ if not os.path.isabs(value):
+ value = os.path.join(self.base, value)
+ with codecs.open(value, 'r', encoding='utf-8') as f:
+ result = json.load(f)
+ return result
+
+
+class SubprocessMixin(object):
+ """
+ Mixin for running subprocesses and capturing their output
+ """
+
+ def __init__(self, verbose=False, progress=None):
+ self.verbose = verbose
+ self.progress = progress
+
+ def reader(self, stream, context):
+ """
+ Read lines from a subprocess' output stream and either pass to a progress
+ callable (if specified) or write progress information to sys.stderr.
+ """
+ progress = self.progress
+ verbose = self.verbose
+ while True:
+ s = stream.readline()
+ if not s:
+ break
+ if progress is not None:
+ progress(s, context)
+ else:
+ if not verbose:
+ sys.stderr.write('.')
+ else:
+ sys.stderr.write(s.decode('utf-8'))
+ sys.stderr.flush()
+ stream.close()
+
+ def run_command(self, cmd, **kwargs):
+ p = subprocess.Popen(cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **kwargs)
+ t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
+ t1.start()
+ t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))
+ t2.start()
+ p.wait()
+ t1.join()
+ t2.join()
+ if self.progress is not None:
+ self.progress('done.', 'main')
+ elif self.verbose:
+ sys.stderr.write('done.\n')
+ return p
+
+
+def normalize_name(name):
+ """Normalize a python package name a la PEP 503"""
+ # https://www.python.org/dev/peps/pep-0503/#normalized-names
+ return re.sub('[-_.]+', '-', name).lower()
+
+
+# def _get_pypirc_command():
+# """
+# Get the distutils command for interacting with PyPI configurations.
+# :return: the command.
+# """
+# from distutils.core import Distribution
+# from distutils.config import PyPIRCCommand
+# d = Distribution()
+# return PyPIRCCommand(d)
+
+
+class PyPIRCFile(object):
+
+ DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
+ DEFAULT_REALM = 'pypi'
+
+ def __init__(self, fn=None, url=None):
+ if fn is None:
+ fn = os.path.join(os.path.expanduser('~'), '.pypirc')
+ self.filename = fn
+ self.url = url
+
+ def read(self):
+ result = {}
+
+ if os.path.exists(self.filename):
+ repository = self.url or self.DEFAULT_REPOSITORY
+
+ config = configparser.RawConfigParser()
+ config.read(self.filename)
+ sections = config.sections()
+ if 'distutils' in sections:
+ # let's get the list of servers
+ index_servers = config.get('distutils', 'index-servers')
+ _servers = [
+ server.strip() for server in index_servers.split('\n')
+ if server.strip() != ''
+ ]
+ if _servers == []:
+ # nothing set, let's try to get the default pypi
+ if 'pypi' in sections:
+ _servers = ['pypi']
+ else:
+ for server in _servers:
+ result = {'server': server}
+ result['username'] = config.get(server, 'username')
+
+ # optional params
+ for key, default in (('repository',
+ self.DEFAULT_REPOSITORY),
+ ('realm', self.DEFAULT_REALM),
+ ('password', None)):
+ if config.has_option(server, key):
+ result[key] = config.get(server, key)
+ else:
+ result[key] = default
+
+ # work around people having "repository" for the "pypi"
+ # section of their config set to the HTTP (rather than
+ # HTTPS) URL
+ if (server == 'pypi' and repository
+ in (self.DEFAULT_REPOSITORY, 'pypi')):
+ result['repository'] = self.DEFAULT_REPOSITORY
+ elif (result['server'] != repository
+ and result['repository'] != repository):
+ result = {}
+ elif 'server-login' in sections:
+ # old format
+ server = 'server-login'
+ if config.has_option(server, 'repository'):
+ repository = config.get(server, 'repository')
+ else:
+ repository = self.DEFAULT_REPOSITORY
+ result = {
+ 'username': config.get(server, 'username'),
+ 'password': config.get(server, 'password'),
+ 'repository': repository,
+ 'server': server,
+ 'realm': self.DEFAULT_REALM
+ }
+ return result
+
+ def update(self, username, password):
+ # import pdb; pdb.set_trace()
+ config = configparser.RawConfigParser()
+ fn = self.filename
+ config.read(fn)
+ if not config.has_section('pypi'):
+ config.add_section('pypi')
+ config.set('pypi', 'username', username)
+ config.set('pypi', 'password', password)
+ with open(fn, 'w') as f:
+ config.write(f)
+
+
+def _load_pypirc(index):
+ """
+ Read the PyPI access configuration as supported by distutils.
+ """
+ return PyPIRCFile(url=index.url).read()
+
+
+def _store_pypirc(index):
+ PyPIRCFile().update(index.username, index.password)
+
+
+#
+# get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor
+# tweaks
+#
+
+
+def get_host_platform():
+ """Return a string that identifies the current platform. This is used mainly to
+ distinguish platform-specific build directories and platform-specific built
+ distributions. Typically includes the OS name and version and the
+ architecture (as supplied by 'os.uname()'), although the exact information
+ included depends on the OS; eg. on Linux, the kernel version isn't
+ particularly important.
+
+ Examples of returned values:
+ linux-i586
+ linux-alpha (?)
+ solaris-2.6-sun4u
+
+ Windows will return one of:
+ win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
+ win32 (all others - specifically, sys.platform is returned)
+
+ For other non-POSIX platforms, currently just returns 'sys.platform'.
+
+ """
+ if os.name == 'nt':
+ if 'amd64' in sys.version.lower():
+ return 'win-amd64'
+ if '(arm)' in sys.version.lower():
+ return 'win-arm32'
+ if '(arm64)' in sys.version.lower():
+ return 'win-arm64'
+ return sys.platform
+
+ # Set for cross builds explicitly
+ if "_PYTHON_HOST_PLATFORM" in os.environ:
+ return os.environ["_PYTHON_HOST_PLATFORM"]
+
+ if os.name != 'posix' or not hasattr(os, 'uname'):
+ # XXX what about the architecture? NT is Intel or Alpha,
+ # Mac OS is M68k or PPC, etc.
+ return sys.platform
+
+ # Try to distinguish various flavours of Unix
+
+ (osname, host, release, version, machine) = os.uname()
+
+ # Convert the OS name to lowercase, remove '/' characters, and translate
+ # spaces (for "Power Macintosh")
+ osname = osname.lower().replace('/', '')
+ machine = machine.replace(' ', '_').replace('/', '-')
+
+ if osname[:5] == 'linux':
+ # At least on Linux/Intel, 'machine' is the processor --
+ # i386, etc.
+ # XXX what about Alpha, SPARC, etc?
+ return "%s-%s" % (osname, machine)
+
+ elif osname[:5] == 'sunos':
+ if release[0] >= '5': # SunOS 5 == Solaris 2
+ osname = 'solaris'
+ release = '%d.%s' % (int(release[0]) - 3, release[2:])
+ # We can't use 'platform.architecture()[0]' because a
+ # bootstrap problem. We use a dict to get an error
+ # if some suspicious happens.
+ bitness = {2147483647: '32bit', 9223372036854775807: '64bit'}
+ machine += '.%s' % bitness[sys.maxsize]
+ # fall through to standard osname-release-machine representation
+ elif osname[:3] == 'aix':
+ from _aix_support import aix_platform
+ return aix_platform()
+ elif osname[:6] == 'cygwin':
+ osname = 'cygwin'
+ rel_re = re.compile(r'[\d.]+', re.ASCII)
+ m = rel_re.match(release)
+ if m:
+ release = m.group()
+ elif osname[:6] == 'darwin':
+ import _osx_support
+ try:
+ from distutils import sysconfig
+ except ImportError:
+ import sysconfig
+ osname, release, machine = _osx_support.get_platform_osx(
+ sysconfig.get_config_vars(), osname, release, machine)
+
+ return '%s-%s-%s' % (osname, release, machine)
+
+
+_TARGET_TO_PLAT = {
+ 'x86': 'win32',
+ 'x64': 'win-amd64',
+ 'arm': 'win-arm32',
+}
+
+
+def get_platform():
+ if os.name != 'nt':
+ return get_host_platform()
+ cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')
+ if cross_compilation_target not in _TARGET_TO_PLAT:
+ return get_host_platform()
+ return _TARGET_TO_PLAT[cross_compilation_target]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..14171ac938df2da628b87cce85f36d4032b3f49c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/version.py
@@ -0,0 +1,751 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2012-2023 The Python Software Foundation.
+# See LICENSE.txt and CONTRIBUTORS.txt.
+#
+"""
+Implementation of a flexible versioning scheme providing support for PEP-440,
+setuptools-compatible and semantic versioning.
+"""
+
+import logging
+import re
+
+from .compat import string_types
+from .util import parse_requirement
+
+__all__ = ['NormalizedVersion', 'NormalizedMatcher',
+ 'LegacyVersion', 'LegacyMatcher',
+ 'SemanticVersion', 'SemanticMatcher',
+ 'UnsupportedVersionError', 'get_scheme']
+
+logger = logging.getLogger(__name__)
+
+
+class UnsupportedVersionError(ValueError):
+ """This is an unsupported version."""
+ pass
+
+
+class Version(object):
+ def __init__(self, s):
+ self._string = s = s.strip()
+ self._parts = parts = self.parse(s)
+ assert isinstance(parts, tuple)
+ assert len(parts) > 0
+
+ def parse(self, s):
+ raise NotImplementedError('please implement in a subclass')
+
+ def _check_compatible(self, other):
+ if type(self) != type(other):
+ raise TypeError('cannot compare %r and %r' % (self, other))
+
+ def __eq__(self, other):
+ self._check_compatible(other)
+ return self._parts == other._parts
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __lt__(self, other):
+ self._check_compatible(other)
+ return self._parts < other._parts
+
+ def __gt__(self, other):
+ return not (self.__lt__(other) or self.__eq__(other))
+
+ def __le__(self, other):
+ return self.__lt__(other) or self.__eq__(other)
+
+ def __ge__(self, other):
+ return self.__gt__(other) or self.__eq__(other)
+
+ # See http://docs.python.org/reference/datamodel#object.__hash__
+ def __hash__(self):
+ return hash(self._parts)
+
+ def __repr__(self):
+ return "%s('%s')" % (self.__class__.__name__, self._string)
+
+ def __str__(self):
+ return self._string
+
+ @property
+ def is_prerelease(self):
+ raise NotImplementedError('Please implement in subclasses.')
+
+
+class Matcher(object):
+ version_class = None
+
+ # value is either a callable or the name of a method
+ _operators = {
+ '<': lambda v, c, p: v < c,
+ '>': lambda v, c, p: v > c,
+ '<=': lambda v, c, p: v == c or v < c,
+ '>=': lambda v, c, p: v == c or v > c,
+ '==': lambda v, c, p: v == c,
+ '===': lambda v, c, p: v == c,
+ # by default, compatible => >=.
+ '~=': lambda v, c, p: v == c or v > c,
+ '!=': lambda v, c, p: v != c,
+ }
+
+ # this is a method only to support alternative implementations
+ # via overriding
+ def parse_requirement(self, s):
+ return parse_requirement(s)
+
+ def __init__(self, s):
+ if self.version_class is None:
+ raise ValueError('Please specify a version class')
+ self._string = s = s.strip()
+ r = self.parse_requirement(s)
+ if not r:
+ raise ValueError('Not valid: %r' % s)
+ self.name = r.name
+ self.key = self.name.lower() # for case-insensitive comparisons
+ clist = []
+ if r.constraints:
+ # import pdb; pdb.set_trace()
+ for op, s in r.constraints:
+ if s.endswith('.*'):
+ if op not in ('==', '!='):
+ raise ValueError('\'.*\' not allowed for '
+ '%r constraints' % op)
+ # Could be a partial version (e.g. for '2.*') which
+ # won't parse as a version, so keep it as a string
+ vn, prefix = s[:-2], True
+ # Just to check that vn is a valid version
+ self.version_class(vn)
+ else:
+ # Should parse as a version, so we can create an
+ # instance for the comparison
+ vn, prefix = self.version_class(s), False
+ clist.append((op, vn, prefix))
+ self._parts = tuple(clist)
+
+ def match(self, version):
+ """
+ Check if the provided version matches the constraints.
+
+ :param version: The version to match against this instance.
+ :type version: String or :class:`Version` instance.
+ """
+ if isinstance(version, string_types):
+ version = self.version_class(version)
+ for operator, constraint, prefix in self._parts:
+ f = self._operators.get(operator)
+ if isinstance(f, string_types):
+ f = getattr(self, f)
+ if not f:
+ msg = ('%r not implemented '
+ 'for %s' % (operator, self.__class__.__name__))
+ raise NotImplementedError(msg)
+ if not f(version, constraint, prefix):
+ return False
+ return True
+
+ @property
+ def exact_version(self):
+ result = None
+ if len(self._parts) == 1 and self._parts[0][0] in ('==', '==='):
+ result = self._parts[0][1]
+ return result
+
+ def _check_compatible(self, other):
+ if type(self) != type(other) or self.name != other.name:
+ raise TypeError('cannot compare %s and %s' % (self, other))
+
+ def __eq__(self, other):
+ self._check_compatible(other)
+ return self.key == other.key and self._parts == other._parts
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ # See http://docs.python.org/reference/datamodel#object.__hash__
+ def __hash__(self):
+ return hash(self.key) + hash(self._parts)
+
+ def __repr__(self):
+ return "%s(%r)" % (self.__class__.__name__, self._string)
+
+ def __str__(self):
+ return self._string
+
+
+PEP440_VERSION_RE = re.compile(r'^v?(\d+!)?(\d+(\.\d+)*)((a|alpha|b|beta|c|rc|pre|preview)(\d+)?)?'
+ r'(\.(post|r|rev)(\d+)?)?([._-]?(dev)(\d+)?)?'
+ r'(\+([a-zA-Z\d]+(\.[a-zA-Z\d]+)?))?$', re.I)
+
+
+def _pep_440_key(s):
+ s = s.strip()
+ m = PEP440_VERSION_RE.match(s)
+ if not m:
+ raise UnsupportedVersionError('Not a valid version: %s' % s)
+ groups = m.groups()
+ nums = tuple(int(v) for v in groups[1].split('.'))
+ while len(nums) > 1 and nums[-1] == 0:
+ nums = nums[:-1]
+
+ if not groups[0]:
+ epoch = 0
+ else:
+ epoch = int(groups[0][:-1])
+ pre = groups[4:6]
+ post = groups[7:9]
+ dev = groups[10:12]
+ local = groups[13]
+ if pre == (None, None):
+ pre = ()
+ else:
+ if pre[1] is None:
+ pre = pre[0], 0
+ else:
+ pre = pre[0], int(pre[1])
+ if post == (None, None):
+ post = ()
+ else:
+ if post[1] is None:
+ post = post[0], 0
+ else:
+ post = post[0], int(post[1])
+ if dev == (None, None):
+ dev = ()
+ else:
+ if dev[1] is None:
+ dev = dev[0], 0
+ else:
+ dev = dev[0], int(dev[1])
+ if local is None:
+ local = ()
+ else:
+ parts = []
+ for part in local.split('.'):
+ # to ensure that numeric compares as > lexicographic, avoid
+ # comparing them directly, but encode a tuple which ensures
+ # correct sorting
+ if part.isdigit():
+ part = (1, int(part))
+ else:
+ part = (0, part)
+ parts.append(part)
+ local = tuple(parts)
+ if not pre:
+ # either before pre-release, or final release and after
+ if not post and dev:
+ # before pre-release
+ pre = ('a', -1) # to sort before a0
+ else:
+ pre = ('z',) # to sort after all pre-releases
+ # now look at the state of post and dev.
+ if not post:
+ post = ('_',) # sort before 'a'
+ if not dev:
+ dev = ('final',)
+
+ return epoch, nums, pre, post, dev, local
+
+
+_normalized_key = _pep_440_key
+
+
+class NormalizedVersion(Version):
+ """A rational version.
+
+ Good:
+ 1.2 # equivalent to "1.2.0"
+ 1.2.0
+ 1.2a1
+ 1.2.3a2
+ 1.2.3b1
+ 1.2.3c1
+ 1.2.3.4
+ TODO: fill this out
+
+ Bad:
+ 1 # minimum two numbers
+ 1.2a # release level must have a release serial
+ 1.2.3b
+ """
+ def parse(self, s):
+ result = _normalized_key(s)
+ # _normalized_key loses trailing zeroes in the release
+ # clause, since that's needed to ensure that X.Y == X.Y.0 == X.Y.0.0
+ # However, PEP 440 prefix matching needs it: for example,
+ # (~= 1.4.5.0) matches differently to (~= 1.4.5.0.0).
+ m = PEP440_VERSION_RE.match(s) # must succeed
+ groups = m.groups()
+ self._release_clause = tuple(int(v) for v in groups[1].split('.'))
+ return result
+
+ PREREL_TAGS = set(['a', 'b', 'c', 'rc', 'dev'])
+
+ @property
+ def is_prerelease(self):
+ return any(t[0] in self.PREREL_TAGS for t in self._parts if t)
+
+
+def _match_prefix(x, y):
+ x = str(x)
+ y = str(y)
+ if x == y:
+ return True
+ if not x.startswith(y):
+ return False
+ n = len(y)
+ return x[n] == '.'
+
+
+class NormalizedMatcher(Matcher):
+ version_class = NormalizedVersion
+
+ # value is either a callable or the name of a method
+ _operators = {
+ '~=': '_match_compatible',
+ '<': '_match_lt',
+ '>': '_match_gt',
+ '<=': '_match_le',
+ '>=': '_match_ge',
+ '==': '_match_eq',
+ '===': '_match_arbitrary',
+ '!=': '_match_ne',
+ }
+
+ def _adjust_local(self, version, constraint, prefix):
+ if prefix:
+ strip_local = '+' not in constraint and version._parts[-1]
+ else:
+ # both constraint and version are
+ # NormalizedVersion instances.
+ # If constraint does not have a local component,
+ # ensure the version doesn't, either.
+ strip_local = not constraint._parts[-1] and version._parts[-1]
+ if strip_local:
+ s = version._string.split('+', 1)[0]
+ version = self.version_class(s)
+ return version, constraint
+
+ def _match_lt(self, version, constraint, prefix):
+ version, constraint = self._adjust_local(version, constraint, prefix)
+ if version >= constraint:
+ return False
+ release_clause = constraint._release_clause
+ pfx = '.'.join([str(i) for i in release_clause])
+ return not _match_prefix(version, pfx)
+
+ def _match_gt(self, version, constraint, prefix):
+ version, constraint = self._adjust_local(version, constraint, prefix)
+ if version <= constraint:
+ return False
+ release_clause = constraint._release_clause
+ pfx = '.'.join([str(i) for i in release_clause])
+ return not _match_prefix(version, pfx)
+
+ def _match_le(self, version, constraint, prefix):
+ version, constraint = self._adjust_local(version, constraint, prefix)
+ return version <= constraint
+
+ def _match_ge(self, version, constraint, prefix):
+ version, constraint = self._adjust_local(version, constraint, prefix)
+ return version >= constraint
+
+ def _match_eq(self, version, constraint, prefix):
+ version, constraint = self._adjust_local(version, constraint, prefix)
+ if not prefix:
+ result = (version == constraint)
+ else:
+ result = _match_prefix(version, constraint)
+ return result
+
+ def _match_arbitrary(self, version, constraint, prefix):
+ return str(version) == str(constraint)
+
+ def _match_ne(self, version, constraint, prefix):
+ version, constraint = self._adjust_local(version, constraint, prefix)
+ if not prefix:
+ result = (version != constraint)
+ else:
+ result = not _match_prefix(version, constraint)
+ return result
+
+ def _match_compatible(self, version, constraint, prefix):
+ version, constraint = self._adjust_local(version, constraint, prefix)
+ if version == constraint:
+ return True
+ if version < constraint:
+ return False
+# if not prefix:
+# return True
+ release_clause = constraint._release_clause
+ if len(release_clause) > 1:
+ release_clause = release_clause[:-1]
+ pfx = '.'.join([str(i) for i in release_clause])
+ return _match_prefix(version, pfx)
+
+
+_REPLACEMENTS = (
+ (re.compile('[.+-]$'), ''), # remove trailing puncts
+ (re.compile(r'^[.](\d)'), r'0.\1'), # .N -> 0.N at start
+ (re.compile('^[.-]'), ''), # remove leading puncts
+ (re.compile(r'^\((.*)\)$'), r'\1'), # remove parentheses
+ (re.compile(r'^v(ersion)?\s*(\d+)'), r'\2'), # remove leading v(ersion)
+ (re.compile(r'^r(ev)?\s*(\d+)'), r'\2'), # remove leading v(ersion)
+ (re.compile('[.]{2,}'), '.'), # multiple runs of '.'
+ (re.compile(r'\b(alfa|apha)\b'), 'alpha'), # misspelt alpha
+ (re.compile(r'\b(pre-alpha|prealpha)\b'),
+ 'pre.alpha'), # standardise
+ (re.compile(r'\(beta\)$'), 'beta'), # remove parentheses
+)
+
+_SUFFIX_REPLACEMENTS = (
+ (re.compile('^[:~._+-]+'), ''), # remove leading puncts
+ (re.compile('[,*")([\\]]'), ''), # remove unwanted chars
+ (re.compile('[~:+_ -]'), '.'), # replace illegal chars
+ (re.compile('[.]{2,}'), '.'), # multiple runs of '.'
+ (re.compile(r'\.$'), ''), # trailing '.'
+)
+
+_NUMERIC_PREFIX = re.compile(r'(\d+(\.\d+)*)')
+
+
+def _suggest_semantic_version(s):
+ """
+ Try to suggest a semantic form for a version for which
+ _suggest_normalized_version couldn't come up with anything.
+ """
+ result = s.strip().lower()
+ for pat, repl in _REPLACEMENTS:
+ result = pat.sub(repl, result)
+ if not result:
+ result = '0.0.0'
+
+ # Now look for numeric prefix, and separate it out from
+ # the rest.
+ # import pdb; pdb.set_trace()
+ m = _NUMERIC_PREFIX.match(result)
+ if not m:
+ prefix = '0.0.0'
+ suffix = result
+ else:
+ prefix = m.groups()[0].split('.')
+ prefix = [int(i) for i in prefix]
+ while len(prefix) < 3:
+ prefix.append(0)
+ if len(prefix) == 3:
+ suffix = result[m.end():]
+ else:
+ suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():]
+ prefix = prefix[:3]
+ prefix = '.'.join([str(i) for i in prefix])
+ suffix = suffix.strip()
+ if suffix:
+ # import pdb; pdb.set_trace()
+ # massage the suffix.
+ for pat, repl in _SUFFIX_REPLACEMENTS:
+ suffix = pat.sub(repl, suffix)
+
+ if not suffix:
+ result = prefix
+ else:
+ sep = '-' if 'dev' in suffix else '+'
+ result = prefix + sep + suffix
+ if not is_semver(result):
+ result = None
+ return result
+
+
+def _suggest_normalized_version(s):
+ """Suggest a normalized version close to the given version string.
+
+ If you have a version string that isn't rational (i.e. NormalizedVersion
+ doesn't like it) then you might be able to get an equivalent (or close)
+ rational version from this function.
+
+ This does a number of simple normalizations to the given string, based
+ on observation of versions currently in use on PyPI. Given a dump of
+ those version during PyCon 2009, 4287 of them:
+ - 2312 (53.93%) match NormalizedVersion without change
+ with the automatic suggestion
+ - 3474 (81.04%) match when using this suggestion method
+
+ @param s {str} An irrational version string.
+ @returns A rational version string, or None, if couldn't determine one.
+ """
+ try:
+ _normalized_key(s)
+ return s # already rational
+ except UnsupportedVersionError:
+ pass
+
+ rs = s.lower()
+
+ # part of this could use maketrans
+ for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'),
+ ('beta', 'b'), ('rc', 'c'), ('-final', ''),
+ ('-pre', 'c'),
+ ('-release', ''), ('.release', ''), ('-stable', ''),
+ ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''),
+ ('final', '')):
+ rs = rs.replace(orig, repl)
+
+ # if something ends with dev or pre, we add a 0
+ rs = re.sub(r"pre$", r"pre0", rs)
+ rs = re.sub(r"dev$", r"dev0", rs)
+
+ # if we have something like "b-2" or "a.2" at the end of the
+ # version, that is probably beta, alpha, etc
+ # let's remove the dash or dot
+ rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs)
+
+ # 1.0-dev-r371 -> 1.0.dev371
+ # 0.1-dev-r79 -> 0.1.dev79
+ rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs)
+
+ # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1
+ rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs)
+
+ # Clean: v0.3, v1.0
+ if rs.startswith('v'):
+ rs = rs[1:]
+
+ # Clean leading '0's on numbers.
+ # TODO: unintended side-effect on, e.g., "2003.05.09"
+ # PyPI stats: 77 (~2%) better
+ rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs)
+
+ # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers
+ # zero.
+ # PyPI stats: 245 (7.56%) better
+ rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs)
+
+ # the 'dev-rNNN' tag is a dev tag
+ rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs)
+
+ # clean the - when used as a pre delimiter
+ rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs)
+
+ # a terminal "dev" or "devel" can be changed into ".dev0"
+ rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs)
+
+ # a terminal "dev" can be changed into ".dev0"
+ rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs)
+
+ # a terminal "final" or "stable" can be removed
+ rs = re.sub(r"(final|stable)$", "", rs)
+
+ # The 'r' and the '-' tags are post release tags
+ # 0.4a1.r10 -> 0.4a1.post10
+ # 0.9.33-17222 -> 0.9.33.post17222
+ # 0.9.33-r17222 -> 0.9.33.post17222
+ rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs)
+
+ # Clean 'r' instead of 'dev' usage:
+ # 0.9.33+r17222 -> 0.9.33.dev17222
+ # 1.0dev123 -> 1.0.dev123
+ # 1.0.git123 -> 1.0.dev123
+ # 1.0.bzr123 -> 1.0.dev123
+ # 0.1a0dev.123 -> 0.1a0.dev123
+ # PyPI stats: ~150 (~4%) better
+ rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs)
+
+ # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage:
+ # 0.2.pre1 -> 0.2c1
+ # 0.2-c1 -> 0.2c1
+ # 1.0preview123 -> 1.0c123
+ # PyPI stats: ~21 (0.62%) better
+ rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs)
+
+ # Tcl/Tk uses "px" for their post release markers
+ rs = re.sub(r"p(\d+)$", r".post\1", rs)
+
+ try:
+ _normalized_key(rs)
+ except UnsupportedVersionError:
+ rs = None
+ return rs
+
+#
+# Legacy version processing (distribute-compatible)
+#
+
+
+_VERSION_PART = re.compile(r'([a-z]+|\d+|[\.-])', re.I)
+_VERSION_REPLACE = {
+ 'pre': 'c',
+ 'preview': 'c',
+ '-': 'final-',
+ 'rc': 'c',
+ 'dev': '@',
+ '': None,
+ '.': None,
+}
+
+
+def _legacy_key(s):
+ def get_parts(s):
+ result = []
+ for p in _VERSION_PART.split(s.lower()):
+ p = _VERSION_REPLACE.get(p, p)
+ if p:
+ if '0' <= p[:1] <= '9':
+ p = p.zfill(8)
+ else:
+ p = '*' + p
+ result.append(p)
+ result.append('*final')
+ return result
+
+ result = []
+ for p in get_parts(s):
+ if p.startswith('*'):
+ if p < '*final':
+ while result and result[-1] == '*final-':
+ result.pop()
+ while result and result[-1] == '00000000':
+ result.pop()
+ result.append(p)
+ return tuple(result)
+
+
+class LegacyVersion(Version):
+ def parse(self, s):
+ return _legacy_key(s)
+
+ @property
+ def is_prerelease(self):
+ result = False
+ for x in self._parts:
+ if (isinstance(x, string_types) and x.startswith('*') and
+ x < '*final'):
+ result = True
+ break
+ return result
+
+
+class LegacyMatcher(Matcher):
+ version_class = LegacyVersion
+
+ _operators = dict(Matcher._operators)
+ _operators['~='] = '_match_compatible'
+
+ numeric_re = re.compile(r'^(\d+(\.\d+)*)')
+
+ def _match_compatible(self, version, constraint, prefix):
+ if version < constraint:
+ return False
+ m = self.numeric_re.match(str(constraint))
+ if not m:
+ logger.warning('Cannot compute compatible match for version %s '
+ ' and constraint %s', version, constraint)
+ return True
+ s = m.groups()[0]
+ if '.' in s:
+ s = s.rsplit('.', 1)[0]
+ return _match_prefix(version, s)
+
+#
+# Semantic versioning
+#
+
+
+_SEMVER_RE = re.compile(r'^(\d+)\.(\d+)\.(\d+)'
+ r'(-[a-z0-9]+(\.[a-z0-9-]+)*)?'
+ r'(\+[a-z0-9]+(\.[a-z0-9-]+)*)?$', re.I)
+
+
+def is_semver(s):
+ return _SEMVER_RE.match(s)
+
+
+def _semantic_key(s):
+ def make_tuple(s, absent):
+ if s is None:
+ result = (absent,)
+ else:
+ parts = s[1:].split('.')
+ # We can't compare ints and strings on Python 3, so fudge it
+ # by zero-filling numeric values so simulate a numeric comparison
+ result = tuple([p.zfill(8) if p.isdigit() else p for p in parts])
+ return result
+
+ m = is_semver(s)
+ if not m:
+ raise UnsupportedVersionError(s)
+ groups = m.groups()
+ major, minor, patch = [int(i) for i in groups[:3]]
+ # choose the '|' and '*' so that versions sort correctly
+ pre, build = make_tuple(groups[3], '|'), make_tuple(groups[5], '*')
+ return (major, minor, patch), pre, build
+
+
+class SemanticVersion(Version):
+ def parse(self, s):
+ return _semantic_key(s)
+
+ @property
+ def is_prerelease(self):
+ return self._parts[1][0] != '|'
+
+
+class SemanticMatcher(Matcher):
+ version_class = SemanticVersion
+
+
+class VersionScheme(object):
+ def __init__(self, key, matcher, suggester=None):
+ self.key = key
+ self.matcher = matcher
+ self.suggester = suggester
+
+ def is_valid_version(self, s):
+ try:
+ self.matcher.version_class(s)
+ result = True
+ except UnsupportedVersionError:
+ result = False
+ return result
+
+ def is_valid_matcher(self, s):
+ try:
+ self.matcher(s)
+ result = True
+ except UnsupportedVersionError:
+ result = False
+ return result
+
+ def is_valid_constraint_list(self, s):
+ """
+ Used for processing some metadata fields
+ """
+ # See issue #140. Be tolerant of a single trailing comma.
+ if s.endswith(','):
+ s = s[:-1]
+ return self.is_valid_matcher('dummy_name (%s)' % s)
+
+ def suggest(self, s):
+ if self.suggester is None:
+ result = None
+ else:
+ result = self.suggester(s)
+ return result
+
+
+_SCHEMES = {
+ 'normalized': VersionScheme(_normalized_key, NormalizedMatcher,
+ _suggest_normalized_version),
+ 'legacy': VersionScheme(_legacy_key, LegacyMatcher, lambda self, s: s),
+ 'semantic': VersionScheme(_semantic_key, SemanticMatcher,
+ _suggest_semantic_version),
+}
+
+_SCHEMES['default'] = _SCHEMES['normalized']
+
+
+def get_scheme(name):
+ if name not in _SCHEMES:
+ raise ValueError('unknown scheme name: %r' % name)
+ return _SCHEMES[name]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/w32.exe b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/w32.exe
new file mode 100644
index 0000000000000000000000000000000000000000..4ee2d3a31b59e8b50f433ecdf0be9e496e8cc3b8
Binary files /dev/null and b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/w32.exe differ
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/wheel.py b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a5a30e1d8d6cd3ae99b38f8c5aafd8d6727df14
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/distlib/wheel.py
@@ -0,0 +1,1099 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2013-2023 Vinay Sajip.
+# Licensed to the Python Software Foundation under a contributor agreement.
+# See LICENSE.txt and CONTRIBUTORS.txt.
+#
+from __future__ import unicode_literals
+
+import base64
+import codecs
+import datetime
+from email import message_from_file
+import hashlib
+import json
+import logging
+import os
+import posixpath
+import re
+import shutil
+import sys
+import tempfile
+import zipfile
+
+from . import __version__, DistlibException
+from .compat import sysconfig, ZipFile, fsdecode, text_type, filter
+from .database import InstalledDistribution
+from .metadata import Metadata, WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME
+from .util import (FileOperator, convert_path, CSVReader, CSVWriter, Cache,
+ cached_property, get_cache_base, read_exports, tempdir,
+ get_platform)
+from .version import NormalizedVersion, UnsupportedVersionError
+
+logger = logging.getLogger(__name__)
+
+cache = None # created when needed
+
+if hasattr(sys, 'pypy_version_info'): # pragma: no cover
+ IMP_PREFIX = 'pp'
+elif sys.platform.startswith('java'): # pragma: no cover
+ IMP_PREFIX = 'jy'
+elif sys.platform == 'cli': # pragma: no cover
+ IMP_PREFIX = 'ip'
+else:
+ IMP_PREFIX = 'cp'
+
+VER_SUFFIX = sysconfig.get_config_var('py_version_nodot')
+if not VER_SUFFIX: # pragma: no cover
+ VER_SUFFIX = '%s%s' % sys.version_info[:2]
+PYVER = 'py' + VER_SUFFIX
+IMPVER = IMP_PREFIX + VER_SUFFIX
+
+ARCH = get_platform().replace('-', '_').replace('.', '_')
+
+ABI = sysconfig.get_config_var('SOABI')
+if ABI and ABI.startswith('cpython-'):
+ ABI = ABI.replace('cpython-', 'cp').split('-')[0]
+else:
+
+ def _derive_abi():
+ parts = ['cp', VER_SUFFIX]
+ if sysconfig.get_config_var('Py_DEBUG'):
+ parts.append('d')
+ if IMP_PREFIX == 'cp':
+ vi = sys.version_info[:2]
+ if vi < (3, 8):
+ wpm = sysconfig.get_config_var('WITH_PYMALLOC')
+ if wpm is None:
+ wpm = True
+ if wpm:
+ parts.append('m')
+ if vi < (3, 3):
+ us = sysconfig.get_config_var('Py_UNICODE_SIZE')
+ if us == 4 or (us is None and sys.maxunicode == 0x10FFFF):
+ parts.append('u')
+ return ''.join(parts)
+
+ ABI = _derive_abi()
+ del _derive_abi
+
+FILENAME_RE = re.compile(
+ r'''
+(?P[^-]+)
+-(?P\d+[^-]*)
+(-(?P\d+[^-]*))?
+-(?P\w+\d+(\.\w+\d+)*)
+-(?P\w+)
+-(?P\w+(\.\w+)*)
+\.whl$
+''', re.IGNORECASE | re.VERBOSE)
+
+NAME_VERSION_RE = re.compile(
+ r'''
+(?P[^-]+)
+-(?P\d+[^-]*)
+(-(?P\d+[^-]*))?$
+''', re.IGNORECASE | re.VERBOSE)
+
+SHEBANG_RE = re.compile(br'\s*#![^\r\n]*')
+SHEBANG_DETAIL_RE = re.compile(br'^(\s*#!("[^"]+"|\S+))\s+(.*)$')
+SHEBANG_PYTHON = b'#!python'
+SHEBANG_PYTHONW = b'#!pythonw'
+
+if os.sep == '/':
+ to_posix = lambda o: o
+else:
+ to_posix = lambda o: o.replace(os.sep, '/')
+
+if sys.version_info[0] < 3:
+ import imp
+else:
+ imp = None
+ import importlib.machinery
+ import importlib.util
+
+
+def _get_suffixes():
+ if imp:
+ return [s[0] for s in imp.get_suffixes()]
+ else:
+ return importlib.machinery.EXTENSION_SUFFIXES
+
+
+def _load_dynamic(name, path):
+ # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
+ if imp:
+ return imp.load_dynamic(name, path)
+ else:
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+class Mounter(object):
+
+ def __init__(self):
+ self.impure_wheels = {}
+ self.libs = {}
+
+ def add(self, pathname, extensions):
+ self.impure_wheels[pathname] = extensions
+ self.libs.update(extensions)
+
+ def remove(self, pathname):
+ extensions = self.impure_wheels.pop(pathname)
+ for k, v in extensions:
+ if k in self.libs:
+ del self.libs[k]
+
+ def find_module(self, fullname, path=None):
+ if fullname in self.libs:
+ result = self
+ else:
+ result = None
+ return result
+
+ def load_module(self, fullname):
+ if fullname in sys.modules:
+ result = sys.modules[fullname]
+ else:
+ if fullname not in self.libs:
+ raise ImportError('unable to find extension for %s' % fullname)
+ result = _load_dynamic(fullname, self.libs[fullname])
+ result.__loader__ = self
+ parts = fullname.rsplit('.', 1)
+ if len(parts) > 1:
+ result.__package__ = parts[0]
+ return result
+
+
+_hook = Mounter()
+
+
+class Wheel(object):
+ """
+ Class to build and install from Wheel files (PEP 427).
+ """
+
+ wheel_version = (1, 1)
+ hash_kind = 'sha256'
+
+ def __init__(self, filename=None, sign=False, verify=False):
+ """
+ Initialise an instance using a (valid) filename.
+ """
+ self.sign = sign
+ self.should_verify = verify
+ self.buildver = ''
+ self.pyver = [PYVER]
+ self.abi = ['none']
+ self.arch = ['any']
+ self.dirname = os.getcwd()
+ if filename is None:
+ self.name = 'dummy'
+ self.version = '0.1'
+ self._filename = self.filename
+ else:
+ m = NAME_VERSION_RE.match(filename)
+ if m:
+ info = m.groupdict('')
+ self.name = info['nm']
+ # Reinstate the local version separator
+ self.version = info['vn'].replace('_', '-')
+ self.buildver = info['bn']
+ self._filename = self.filename
+ else:
+ dirname, filename = os.path.split(filename)
+ m = FILENAME_RE.match(filename)
+ if not m:
+ raise DistlibException('Invalid name or '
+ 'filename: %r' % filename)
+ if dirname:
+ self.dirname = os.path.abspath(dirname)
+ self._filename = filename
+ info = m.groupdict('')
+ self.name = info['nm']
+ self.version = info['vn']
+ self.buildver = info['bn']
+ self.pyver = info['py'].split('.')
+ self.abi = info['bi'].split('.')
+ self.arch = info['ar'].split('.')
+
+ @property
+ def filename(self):
+ """
+ Build and return a filename from the various components.
+ """
+ if self.buildver:
+ buildver = '-' + self.buildver
+ else:
+ buildver = ''
+ pyver = '.'.join(self.pyver)
+ abi = '.'.join(self.abi)
+ arch = '.'.join(self.arch)
+ # replace - with _ as a local version separator
+ version = self.version.replace('-', '_')
+ return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver,
+ abi, arch)
+
+ @property
+ def exists(self):
+ path = os.path.join(self.dirname, self.filename)
+ return os.path.isfile(path)
+
+ @property
+ def tags(self):
+ for pyver in self.pyver:
+ for abi in self.abi:
+ for arch in self.arch:
+ yield pyver, abi, arch
+
+ @cached_property
+ def metadata(self):
+ pathname = os.path.join(self.dirname, self.filename)
+ name_ver = '%s-%s' % (self.name, self.version)
+ info_dir = '%s.dist-info' % name_ver
+ wrapper = codecs.getreader('utf-8')
+ with ZipFile(pathname, 'r') as zf:
+ self.get_wheel_metadata(zf)
+ # wv = wheel_metadata['Wheel-Version'].split('.', 1)
+ # file_version = tuple([int(i) for i in wv])
+ # if file_version < (1, 1):
+ # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME,
+ # LEGACY_METADATA_FILENAME]
+ # else:
+ # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME]
+ fns = [WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME]
+ result = None
+ for fn in fns:
+ try:
+ metadata_filename = posixpath.join(info_dir, fn)
+ with zf.open(metadata_filename) as bf:
+ wf = wrapper(bf)
+ result = Metadata(fileobj=wf)
+ if result:
+ break
+ except KeyError:
+ pass
+ if not result:
+ raise ValueError('Invalid wheel, because metadata is '
+ 'missing: looked in %s' % ', '.join(fns))
+ return result
+
+ def get_wheel_metadata(self, zf):
+ name_ver = '%s-%s' % (self.name, self.version)
+ info_dir = '%s.dist-info' % name_ver
+ metadata_filename = posixpath.join(info_dir, 'WHEEL')
+ with zf.open(metadata_filename) as bf:
+ wf = codecs.getreader('utf-8')(bf)
+ message = message_from_file(wf)
+ return dict(message)
+
+ @cached_property
+ def info(self):
+ pathname = os.path.join(self.dirname, self.filename)
+ with ZipFile(pathname, 'r') as zf:
+ result = self.get_wheel_metadata(zf)
+ return result
+
+ def process_shebang(self, data):
+ m = SHEBANG_RE.match(data)
+ if m:
+ end = m.end()
+ shebang, data_after_shebang = data[:end], data[end:]
+ # Preserve any arguments after the interpreter
+ if b'pythonw' in shebang.lower():
+ shebang_python = SHEBANG_PYTHONW
+ else:
+ shebang_python = SHEBANG_PYTHON
+ m = SHEBANG_DETAIL_RE.match(shebang)
+ if m:
+ args = b' ' + m.groups()[-1]
+ else:
+ args = b''
+ shebang = shebang_python + args
+ data = shebang + data_after_shebang
+ else:
+ cr = data.find(b'\r')
+ lf = data.find(b'\n')
+ if cr < 0 or cr > lf:
+ term = b'\n'
+ else:
+ if data[cr:cr + 2] == b'\r\n':
+ term = b'\r\n'
+ else:
+ term = b'\r'
+ data = SHEBANG_PYTHON + term + data
+ return data
+
+ def get_hash(self, data, hash_kind=None):
+ if hash_kind is None:
+ hash_kind = self.hash_kind
+ try:
+ hasher = getattr(hashlib, hash_kind)
+ except AttributeError:
+ raise DistlibException('Unsupported hash algorithm: %r' %
+ hash_kind)
+ result = hasher(data).digest()
+ result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii')
+ return hash_kind, result
+
+ def write_record(self, records, record_path, archive_record_path):
+ records = list(records) # make a copy, as mutated
+ records.append((archive_record_path, '', ''))
+ with CSVWriter(record_path) as writer:
+ for row in records:
+ writer.writerow(row)
+
+ def write_records(self, info, libdir, archive_paths):
+ records = []
+ distinfo, info_dir = info
+ # hasher = getattr(hashlib, self.hash_kind)
+ for ap, p in archive_paths:
+ with open(p, 'rb') as f:
+ data = f.read()
+ digest = '%s=%s' % self.get_hash(data)
+ size = os.path.getsize(p)
+ records.append((ap, digest, size))
+
+ p = os.path.join(distinfo, 'RECORD')
+ ap = to_posix(os.path.join(info_dir, 'RECORD'))
+ self.write_record(records, p, ap)
+ archive_paths.append((ap, p))
+
+ def build_zip(self, pathname, archive_paths):
+ with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf:
+ for ap, p in archive_paths:
+ logger.debug('Wrote %s to %s in wheel', p, ap)
+ zf.write(p, ap)
+
+ def build(self, paths, tags=None, wheel_version=None):
+ """
+ Build a wheel from files in specified paths, and use any specified tags
+ when determining the name of the wheel.
+ """
+ if tags is None:
+ tags = {}
+
+ libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]
+ if libkey == 'platlib':
+ is_pure = 'false'
+ default_pyver = [IMPVER]
+ default_abi = [ABI]
+ default_arch = [ARCH]
+ else:
+ is_pure = 'true'
+ default_pyver = [PYVER]
+ default_abi = ['none']
+ default_arch = ['any']
+
+ self.pyver = tags.get('pyver', default_pyver)
+ self.abi = tags.get('abi', default_abi)
+ self.arch = tags.get('arch', default_arch)
+
+ libdir = paths[libkey]
+
+ name_ver = '%s-%s' % (self.name, self.version)
+ data_dir = '%s.data' % name_ver
+ info_dir = '%s.dist-info' % name_ver
+
+ archive_paths = []
+
+ # First, stuff which is not in site-packages
+ for key in ('data', 'headers', 'scripts'):
+ if key not in paths:
+ continue
+ path = paths[key]
+ if os.path.isdir(path):
+ for root, dirs, files in os.walk(path):
+ for fn in files:
+ p = fsdecode(os.path.join(root, fn))
+ rp = os.path.relpath(p, path)
+ ap = to_posix(os.path.join(data_dir, key, rp))
+ archive_paths.append((ap, p))
+ if key == 'scripts' and not p.endswith('.exe'):
+ with open(p, 'rb') as f:
+ data = f.read()
+ data = self.process_shebang(data)
+ with open(p, 'wb') as f:
+ f.write(data)
+
+ # Now, stuff which is in site-packages, other than the
+ # distinfo stuff.
+ path = libdir
+ distinfo = None
+ for root, dirs, files in os.walk(path):
+ if root == path:
+ # At the top level only, save distinfo for later
+ # and skip it for now
+ for i, dn in enumerate(dirs):
+ dn = fsdecode(dn)
+ if dn.endswith('.dist-info'):
+ distinfo = os.path.join(root, dn)
+ del dirs[i]
+ break
+ assert distinfo, '.dist-info directory expected, not found'
+
+ for fn in files:
+ # comment out next suite to leave .pyc files in
+ if fsdecode(fn).endswith(('.pyc', '.pyo')):
+ continue
+ p = os.path.join(root, fn)
+ rp = to_posix(os.path.relpath(p, path))
+ archive_paths.append((rp, p))
+
+ # Now distinfo. Assumed to be flat, i.e. os.listdir is enough.
+ files = os.listdir(distinfo)
+ for fn in files:
+ if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'):
+ p = fsdecode(os.path.join(distinfo, fn))
+ ap = to_posix(os.path.join(info_dir, fn))
+ archive_paths.append((ap, p))
+
+ wheel_metadata = [
+ 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version),
+ 'Generator: distlib %s' % __version__,
+ 'Root-Is-Purelib: %s' % is_pure,
+ ]
+ for pyver, abi, arch in self.tags:
+ wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch))
+ p = os.path.join(distinfo, 'WHEEL')
+ with open(p, 'w') as f:
+ f.write('\n'.join(wheel_metadata))
+ ap = to_posix(os.path.join(info_dir, 'WHEEL'))
+ archive_paths.append((ap, p))
+
+ # sort the entries by archive path. Not needed by any spec, but it
+ # keeps the archive listing and RECORD tidier than they would otherwise
+ # be. Use the number of path segments to keep directory entries together,
+ # and keep the dist-info stuff at the end.
+ def sorter(t):
+ ap = t[0]
+ n = ap.count('/')
+ if '.dist-info' in ap:
+ n += 10000
+ return (n, ap)
+
+ archive_paths = sorted(archive_paths, key=sorter)
+
+ # Now, at last, RECORD.
+ # Paths in here are archive paths - nothing else makes sense.
+ self.write_records((distinfo, info_dir), libdir, archive_paths)
+ # Now, ready to build the zip file
+ pathname = os.path.join(self.dirname, self.filename)
+ self.build_zip(pathname, archive_paths)
+ return pathname
+
+ def skip_entry(self, arcname):
+ """
+ Determine whether an archive entry should be skipped when verifying
+ or installing.
+ """
+ # The signature file won't be in RECORD,
+ # and we don't currently don't do anything with it
+ # We also skip directories, as they won't be in RECORD
+ # either. See:
+ #
+ # https://github.com/pypa/wheel/issues/294
+ # https://github.com/pypa/wheel/issues/287
+ # https://github.com/pypa/wheel/pull/289
+ #
+ return arcname.endswith(('/', '/RECORD.jws'))
+
+ def install(self, paths, maker, **kwargs):
+ """
+ Install a wheel to the specified paths. If kwarg ``warner`` is
+ specified, it should be a callable, which will be called with two
+ tuples indicating the wheel version of this software and the wheel
+ version in the file, if there is a discrepancy in the versions.
+ This can be used to issue any warnings to raise any exceptions.
+ If kwarg ``lib_only`` is True, only the purelib/platlib files are
+ installed, and the headers, scripts, data and dist-info metadata are
+ not written. If kwarg ``bytecode_hashed_invalidation`` is True, written
+ bytecode will try to use file-hash based invalidation (PEP-552) on
+ supported interpreter versions (CPython 2.7+).
+
+ The return value is a :class:`InstalledDistribution` instance unless
+ ``options.lib_only`` is True, in which case the return value is ``None``.
+ """
+
+ dry_run = maker.dry_run
+ warner = kwargs.get('warner')
+ lib_only = kwargs.get('lib_only', False)
+ bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation',
+ False)
+
+ pathname = os.path.join(self.dirname, self.filename)
+ name_ver = '%s-%s' % (self.name, self.version)
+ data_dir = '%s.data' % name_ver
+ info_dir = '%s.dist-info' % name_ver
+
+ metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
+ wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
+ record_name = posixpath.join(info_dir, 'RECORD')
+
+ wrapper = codecs.getreader('utf-8')
+
+ with ZipFile(pathname, 'r') as zf:
+ with zf.open(wheel_metadata_name) as bwf:
+ wf = wrapper(bwf)
+ message = message_from_file(wf)
+ wv = message['Wheel-Version'].split('.', 1)
+ file_version = tuple([int(i) for i in wv])
+ if (file_version != self.wheel_version) and warner:
+ warner(self.wheel_version, file_version)
+
+ if message['Root-Is-Purelib'] == 'true':
+ libdir = paths['purelib']
+ else:
+ libdir = paths['platlib']
+
+ records = {}
+ with zf.open(record_name) as bf:
+ with CSVReader(stream=bf) as reader:
+ for row in reader:
+ p = row[0]
+ records[p] = row
+
+ data_pfx = posixpath.join(data_dir, '')
+ info_pfx = posixpath.join(info_dir, '')
+ script_pfx = posixpath.join(data_dir, 'scripts', '')
+
+ # make a new instance rather than a copy of maker's,
+ # as we mutate it
+ fileop = FileOperator(dry_run=dry_run)
+ fileop.record = True # so we can rollback if needed
+
+ bc = not sys.dont_write_bytecode # Double negatives. Lovely!
+
+ outfiles = [] # for RECORD writing
+
+ # for script copying/shebang processing
+ workdir = tempfile.mkdtemp()
+ # set target dir later
+ # we default add_launchers to False, as the
+ # Python Launcher should be used instead
+ maker.source_dir = workdir
+ maker.target_dir = None
+ try:
+ for zinfo in zf.infolist():
+ arcname = zinfo.filename
+ if isinstance(arcname, text_type):
+ u_arcname = arcname
+ else:
+ u_arcname = arcname.decode('utf-8')
+ if self.skip_entry(u_arcname):
+ continue
+ row = records[u_arcname]
+ if row[2] and str(zinfo.file_size) != row[2]:
+ raise DistlibException('size mismatch for '
+ '%s' % u_arcname)
+ if row[1]:
+ kind, value = row[1].split('=', 1)
+ with zf.open(arcname) as bf:
+ data = bf.read()
+ _, digest = self.get_hash(data, kind)
+ if digest != value:
+ raise DistlibException('digest mismatch for '
+ '%s' % arcname)
+
+ if lib_only and u_arcname.startswith((info_pfx, data_pfx)):
+ logger.debug('lib_only: skipping %s', u_arcname)
+ continue
+ is_script = (u_arcname.startswith(script_pfx)
+ and not u_arcname.endswith('.exe'))
+
+ if u_arcname.startswith(data_pfx):
+ _, where, rp = u_arcname.split('/', 2)
+ outfile = os.path.join(paths[where], convert_path(rp))
+ else:
+ # meant for site-packages.
+ if u_arcname in (wheel_metadata_name, record_name):
+ continue
+ outfile = os.path.join(libdir, convert_path(u_arcname))
+ if not is_script:
+ with zf.open(arcname) as bf:
+ fileop.copy_stream(bf, outfile)
+ # Issue #147: permission bits aren't preserved. Using
+ # zf.extract(zinfo, libdir) should have worked, but didn't,
+ # see https://www.thetopsites.net/article/53834422.shtml
+ # So ... manually preserve permission bits as given in zinfo
+ if os.name == 'posix':
+ # just set the normal permission bits
+ os.chmod(outfile,
+ (zinfo.external_attr >> 16) & 0x1FF)
+ outfiles.append(outfile)
+ # Double check the digest of the written file
+ if not dry_run and row[1]:
+ with open(outfile, 'rb') as bf:
+ data = bf.read()
+ _, newdigest = self.get_hash(data, kind)
+ if newdigest != digest:
+ raise DistlibException('digest mismatch '
+ 'on write for '
+ '%s' % outfile)
+ if bc and outfile.endswith('.py'):
+ try:
+ pyc = fileop.byte_compile(
+ outfile,
+ hashed_invalidation=bc_hashed_invalidation)
+ outfiles.append(pyc)
+ except Exception:
+ # Don't give up if byte-compilation fails,
+ # but log it and perhaps warn the user
+ logger.warning('Byte-compilation failed',
+ exc_info=True)
+ else:
+ fn = os.path.basename(convert_path(arcname))
+ workname = os.path.join(workdir, fn)
+ with zf.open(arcname) as bf:
+ fileop.copy_stream(bf, workname)
+
+ dn, fn = os.path.split(outfile)
+ maker.target_dir = dn
+ filenames = maker.make(fn)
+ fileop.set_executable_mode(filenames)
+ outfiles.extend(filenames)
+
+ if lib_only:
+ logger.debug('lib_only: returning None')
+ dist = None
+ else:
+ # Generate scripts
+
+ # Try to get pydist.json so we can see if there are
+ # any commands to generate. If this fails (e.g. because
+ # of a legacy wheel), log a warning but don't give up.
+ commands = None
+ file_version = self.info['Wheel-Version']
+ if file_version == '1.0':
+ # Use legacy info
+ ep = posixpath.join(info_dir, 'entry_points.txt')
+ try:
+ with zf.open(ep) as bwf:
+ epdata = read_exports(bwf)
+ commands = {}
+ for key in ('console', 'gui'):
+ k = '%s_scripts' % key
+ if k in epdata:
+ commands['wrap_%s' % key] = d = {}
+ for v in epdata[k].values():
+ s = '%s:%s' % (v.prefix, v.suffix)
+ if v.flags:
+ s += ' [%s]' % ','.join(v.flags)
+ d[v.name] = s
+ except Exception:
+ logger.warning('Unable to read legacy script '
+ 'metadata, so cannot generate '
+ 'scripts')
+ else:
+ try:
+ with zf.open(metadata_name) as bwf:
+ wf = wrapper(bwf)
+ commands = json.load(wf).get('extensions')
+ if commands:
+ commands = commands.get('python.commands')
+ except Exception:
+ logger.warning('Unable to read JSON metadata, so '
+ 'cannot generate scripts')
+ if commands:
+ console_scripts = commands.get('wrap_console', {})
+ gui_scripts = commands.get('wrap_gui', {})
+ if console_scripts or gui_scripts:
+ script_dir = paths.get('scripts', '')
+ if not os.path.isdir(script_dir):
+ raise ValueError('Valid script path not '
+ 'specified')
+ maker.target_dir = script_dir
+ for k, v in console_scripts.items():
+ script = '%s = %s' % (k, v)
+ filenames = maker.make(script)
+ fileop.set_executable_mode(filenames)
+
+ if gui_scripts:
+ options = {'gui': True}
+ for k, v in gui_scripts.items():
+ script = '%s = %s' % (k, v)
+ filenames = maker.make(script, options)
+ fileop.set_executable_mode(filenames)
+
+ p = os.path.join(libdir, info_dir)
+ dist = InstalledDistribution(p)
+
+ # Write SHARED
+ paths = dict(paths) # don't change passed in dict
+ del paths['purelib']
+ del paths['platlib']
+ paths['lib'] = libdir
+ p = dist.write_shared_locations(paths, dry_run)
+ if p:
+ outfiles.append(p)
+
+ # Write RECORD
+ dist.write_installed_files(outfiles, paths['prefix'],
+ dry_run)
+ return dist
+ except Exception: # pragma: no cover
+ logger.exception('installation failed.')
+ fileop.rollback()
+ raise
+ finally:
+ shutil.rmtree(workdir)
+
+ def _get_dylib_cache(self):
+ global cache
+ if cache is None:
+ # Use native string to avoid issues on 2.x: see Python #20140.
+ base = os.path.join(get_cache_base(), str('dylib-cache'),
+ '%s.%s' % sys.version_info[:2])
+ cache = Cache(base)
+ return cache
+
+ def _get_extensions(self):
+ pathname = os.path.join(self.dirname, self.filename)
+ name_ver = '%s-%s' % (self.name, self.version)
+ info_dir = '%s.dist-info' % name_ver
+ arcname = posixpath.join(info_dir, 'EXTENSIONS')
+ wrapper = codecs.getreader('utf-8')
+ result = []
+ with ZipFile(pathname, 'r') as zf:
+ try:
+ with zf.open(arcname) as bf:
+ wf = wrapper(bf)
+ extensions = json.load(wf)
+ cache = self._get_dylib_cache()
+ prefix = cache.prefix_to_dir(pathname)
+ cache_base = os.path.join(cache.base, prefix)
+ if not os.path.isdir(cache_base):
+ os.makedirs(cache_base)
+ for name, relpath in extensions.items():
+ dest = os.path.join(cache_base, convert_path(relpath))
+ if not os.path.exists(dest):
+ extract = True
+ else:
+ file_time = os.stat(dest).st_mtime
+ file_time = datetime.datetime.fromtimestamp(
+ file_time)
+ info = zf.getinfo(relpath)
+ wheel_time = datetime.datetime(*info.date_time)
+ extract = wheel_time > file_time
+ if extract:
+ zf.extract(relpath, cache_base)
+ result.append((name, dest))
+ except KeyError:
+ pass
+ return result
+
+ def is_compatible(self):
+ """
+ Determine if a wheel is compatible with the running system.
+ """
+ return is_compatible(self)
+
+ def is_mountable(self):
+ """
+ Determine if a wheel is asserted as mountable by its metadata.
+ """
+ return True # for now - metadata details TBD
+
+ def mount(self, append=False):
+ pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
+ if not self.is_compatible():
+ msg = 'Wheel %s not compatible with this Python.' % pathname
+ raise DistlibException(msg)
+ if not self.is_mountable():
+ msg = 'Wheel %s is marked as not mountable.' % pathname
+ raise DistlibException(msg)
+ if pathname in sys.path:
+ logger.debug('%s already in path', pathname)
+ else:
+ if append:
+ sys.path.append(pathname)
+ else:
+ sys.path.insert(0, pathname)
+ extensions = self._get_extensions()
+ if extensions:
+ if _hook not in sys.meta_path:
+ sys.meta_path.append(_hook)
+ _hook.add(pathname, extensions)
+
+ def unmount(self):
+ pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
+ if pathname not in sys.path:
+ logger.debug('%s not in path', pathname)
+ else:
+ sys.path.remove(pathname)
+ if pathname in _hook.impure_wheels:
+ _hook.remove(pathname)
+ if not _hook.impure_wheels:
+ if _hook in sys.meta_path:
+ sys.meta_path.remove(_hook)
+
+ def verify(self):
+ pathname = os.path.join(self.dirname, self.filename)
+ name_ver = '%s-%s' % (self.name, self.version)
+ # data_dir = '%s.data' % name_ver
+ info_dir = '%s.dist-info' % name_ver
+
+ # metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
+ wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
+ record_name = posixpath.join(info_dir, 'RECORD')
+
+ wrapper = codecs.getreader('utf-8')
+
+ with ZipFile(pathname, 'r') as zf:
+ with zf.open(wheel_metadata_name) as bwf:
+ wf = wrapper(bwf)
+ message_from_file(wf)
+ # wv = message['Wheel-Version'].split('.', 1)
+ # file_version = tuple([int(i) for i in wv])
+ # TODO version verification
+
+ records = {}
+ with zf.open(record_name) as bf:
+ with CSVReader(stream=bf) as reader:
+ for row in reader:
+ p = row[0]
+ records[p] = row
+
+ for zinfo in zf.infolist():
+ arcname = zinfo.filename
+ if isinstance(arcname, text_type):
+ u_arcname = arcname
+ else:
+ u_arcname = arcname.decode('utf-8')
+ # See issue #115: some wheels have .. in their entries, but
+ # in the filename ... e.g. __main__..py ! So the check is
+ # updated to look for .. in the directory portions
+ p = u_arcname.split('/')
+ if '..' in p:
+ raise DistlibException('invalid entry in '
+ 'wheel: %r' % u_arcname)
+
+ if self.skip_entry(u_arcname):
+ continue
+ row = records[u_arcname]
+ if row[2] and str(zinfo.file_size) != row[2]:
+ raise DistlibException('size mismatch for '
+ '%s' % u_arcname)
+ if row[1]:
+ kind, value = row[1].split('=', 1)
+ with zf.open(arcname) as bf:
+ data = bf.read()
+ _, digest = self.get_hash(data, kind)
+ if digest != value:
+ raise DistlibException('digest mismatch for '
+ '%s' % arcname)
+
+ def update(self, modifier, dest_dir=None, **kwargs):
+ """
+ Update the contents of a wheel in a generic way. The modifier should
+ be a callable which expects a dictionary argument: its keys are
+ archive-entry paths, and its values are absolute filesystem paths
+ where the contents the corresponding archive entries can be found. The
+ modifier is free to change the contents of the files pointed to, add
+ new entries and remove entries, before returning. This method will
+ extract the entire contents of the wheel to a temporary location, call
+ the modifier, and then use the passed (and possibly updated)
+ dictionary to write a new wheel. If ``dest_dir`` is specified, the new
+ wheel is written there -- otherwise, the original wheel is overwritten.
+
+ The modifier should return True if it updated the wheel, else False.
+ This method returns the same value the modifier returns.
+ """
+
+ def get_version(path_map, info_dir):
+ version = path = None
+ key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME)
+ if key not in path_map:
+ key = '%s/PKG-INFO' % info_dir
+ if key in path_map:
+ path = path_map[key]
+ version = Metadata(path=path).version
+ return version, path
+
+ def update_version(version, path):
+ updated = None
+ try:
+ NormalizedVersion(version)
+ i = version.find('-')
+ if i < 0:
+ updated = '%s+1' % version
+ else:
+ parts = [int(s) for s in version[i + 1:].split('.')]
+ parts[-1] += 1
+ updated = '%s+%s' % (version[:i], '.'.join(
+ str(i) for i in parts))
+ except UnsupportedVersionError:
+ logger.debug(
+ 'Cannot update non-compliant (PEP-440) '
+ 'version %r', version)
+ if updated:
+ md = Metadata(path=path)
+ md.version = updated
+ legacy = path.endswith(LEGACY_METADATA_FILENAME)
+ md.write(path=path, legacy=legacy)
+ logger.debug('Version updated from %r to %r', version, updated)
+
+ pathname = os.path.join(self.dirname, self.filename)
+ name_ver = '%s-%s' % (self.name, self.version)
+ info_dir = '%s.dist-info' % name_ver
+ record_name = posixpath.join(info_dir, 'RECORD')
+ with tempdir() as workdir:
+ with ZipFile(pathname, 'r') as zf:
+ path_map = {}
+ for zinfo in zf.infolist():
+ arcname = zinfo.filename
+ if isinstance(arcname, text_type):
+ u_arcname = arcname
+ else:
+ u_arcname = arcname.decode('utf-8')
+ if u_arcname == record_name:
+ continue
+ if '..' in u_arcname:
+ raise DistlibException('invalid entry in '
+ 'wheel: %r' % u_arcname)
+ zf.extract(zinfo, workdir)
+ path = os.path.join(workdir, convert_path(u_arcname))
+ path_map[u_arcname] = path
+
+ # Remember the version.
+ original_version, _ = get_version(path_map, info_dir)
+ # Files extracted. Call the modifier.
+ modified = modifier(path_map, **kwargs)
+ if modified:
+ # Something changed - need to build a new wheel.
+ current_version, path = get_version(path_map, info_dir)
+ if current_version and (current_version == original_version):
+ # Add or update local version to signify changes.
+ update_version(current_version, path)
+ # Decide where the new wheel goes.
+ if dest_dir is None:
+ fd, newpath = tempfile.mkstemp(suffix='.whl',
+ prefix='wheel-update-',
+ dir=workdir)
+ os.close(fd)
+ else:
+ if not os.path.isdir(dest_dir):
+ raise DistlibException('Not a directory: %r' %
+ dest_dir)
+ newpath = os.path.join(dest_dir, self.filename)
+ archive_paths = list(path_map.items())
+ distinfo = os.path.join(workdir, info_dir)
+ info = distinfo, info_dir
+ self.write_records(info, workdir, archive_paths)
+ self.build_zip(newpath, archive_paths)
+ if dest_dir is None:
+ shutil.copyfile(newpath, pathname)
+ return modified
+
+
+def _get_glibc_version():
+ import platform
+ ver = platform.libc_ver()
+ result = []
+ if ver[0] == 'glibc':
+ for s in ver[1].split('.'):
+ result.append(int(s) if s.isdigit() else 0)
+ result = tuple(result)
+ return result
+
+
+def compatible_tags():
+ """
+ Return (pyver, abi, arch) tuples compatible with this Python.
+ """
+ versions = [VER_SUFFIX]
+ major = VER_SUFFIX[0]
+ for minor in range(sys.version_info[1] - 1, -1, -1):
+ versions.append(''.join([major, str(minor)]))
+
+ abis = []
+ for suffix in _get_suffixes():
+ if suffix.startswith('.abi'):
+ abis.append(suffix.split('.', 2)[1])
+ abis.sort()
+ if ABI != 'none':
+ abis.insert(0, ABI)
+ abis.append('none')
+ result = []
+
+ arches = [ARCH]
+ if sys.platform == 'darwin':
+ m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', ARCH)
+ if m:
+ name, major, minor, arch = m.groups()
+ minor = int(minor)
+ matches = [arch]
+ if arch in ('i386', 'ppc'):
+ matches.append('fat')
+ if arch in ('i386', 'ppc', 'x86_64'):
+ matches.append('fat3')
+ if arch in ('ppc64', 'x86_64'):
+ matches.append('fat64')
+ if arch in ('i386', 'x86_64'):
+ matches.append('intel')
+ if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):
+ matches.append('universal')
+ while minor >= 0:
+ for match in matches:
+ s = '%s_%s_%s_%s' % (name, major, minor, match)
+ if s != ARCH: # already there
+ arches.append(s)
+ minor -= 1
+
+ # Most specific - our Python version, ABI and arch
+ for abi in abis:
+ for arch in arches:
+ result.append((''.join((IMP_PREFIX, versions[0])), abi, arch))
+ # manylinux
+ if abi != 'none' and sys.platform.startswith('linux'):
+ arch = arch.replace('linux_', '')
+ parts = _get_glibc_version()
+ if len(parts) == 2:
+ if parts >= (2, 5):
+ result.append((''.join((IMP_PREFIX, versions[0])), abi,
+ 'manylinux1_%s' % arch))
+ if parts >= (2, 12):
+ result.append((''.join((IMP_PREFIX, versions[0])), abi,
+ 'manylinux2010_%s' % arch))
+ if parts >= (2, 17):
+ result.append((''.join((IMP_PREFIX, versions[0])), abi,
+ 'manylinux2014_%s' % arch))
+ result.append(
+ (''.join((IMP_PREFIX, versions[0])), abi,
+ 'manylinux_%s_%s_%s' % (parts[0], parts[1], arch)))
+
+ # where no ABI / arch dependency, but IMP_PREFIX dependency
+ for i, version in enumerate(versions):
+ result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))
+ if i == 0:
+ result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))
+
+ # no IMP_PREFIX, ABI or arch dependency
+ for i, version in enumerate(versions):
+ result.append((''.join(('py', version)), 'none', 'any'))
+ if i == 0:
+ result.append((''.join(('py', version[0])), 'none', 'any'))
+
+ return set(result)
+
+
+COMPATIBLE_TAGS = compatible_tags()
+
+del compatible_tags
+
+
+def is_compatible(wheel, tags=None):
+ if not isinstance(wheel, Wheel):
+ wheel = Wheel(wheel) # assume it's a filename
+ result = False
+ if tags is None:
+ tags = COMPATIBLE_TAGS
+ for ver, abi, arch in tags:
+ if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch:
+ result = True
+ break
+ return result
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4249b9e7207639a0932109e5d38e7db0b732fca
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/__init__.py
@@ -0,0 +1,70 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2007, 2009, 2011 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""dnspython DNS toolkit"""
+
+__all__ = [
+ "asyncbackend",
+ "asyncquery",
+ "asyncresolver",
+ "dnssec",
+ "dnssecalgs",
+ "dnssectypes",
+ "e164",
+ "edns",
+ "entropy",
+ "exception",
+ "flags",
+ "immutable",
+ "inet",
+ "ipv4",
+ "ipv6",
+ "message",
+ "name",
+ "namedict",
+ "node",
+ "opcode",
+ "query",
+ "quic",
+ "rcode",
+ "rdata",
+ "rdataclass",
+ "rdataset",
+ "rdatatype",
+ "renderer",
+ "resolver",
+ "reversename",
+ "rrset",
+ "serial",
+ "set",
+ "tokenizer",
+ "transaction",
+ "tsig",
+ "tsigkeyring",
+ "ttl",
+ "rdtypes",
+ "update",
+ "version",
+ "versioned",
+ "wire",
+ "xfr",
+ "zone",
+ "zonetypes",
+ "zonefile",
+]
+
+from dns.version import version as __version__ # noqa
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_asyncbackend.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_asyncbackend.py
new file mode 100644
index 0000000000000000000000000000000000000000..49f14fed682f6088fc506ce19978fbe62da1fafe
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_asyncbackend.py
@@ -0,0 +1,99 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# This is a nullcontext for both sync and async. 3.7 has a nullcontext,
+# but it is only for sync use.
+
+
+class NullContext:
+ def __init__(self, enter_result=None):
+ self.enter_result = enter_result
+
+ def __enter__(self):
+ return self.enter_result
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ pass
+
+ async def __aenter__(self):
+ return self.enter_result
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ pass
+
+
+# These are declared here so backends can import them without creating
+# circular dependencies with dns.asyncbackend.
+
+
+class Socket: # pragma: no cover
+ async def close(self):
+ pass
+
+ async def getpeername(self):
+ raise NotImplementedError
+
+ async def getsockname(self):
+ raise NotImplementedError
+
+ async def getpeercert(self, timeout):
+ raise NotImplementedError
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.close()
+
+
+class DatagramSocket(Socket): # pragma: no cover
+ def __init__(self, family: int):
+ self.family = family
+
+ async def sendto(self, what, destination, timeout):
+ raise NotImplementedError
+
+ async def recvfrom(self, size, timeout):
+ raise NotImplementedError
+
+
+class StreamSocket(Socket): # pragma: no cover
+ async def sendall(self, what, timeout):
+ raise NotImplementedError
+
+ async def recv(self, size, timeout):
+ raise NotImplementedError
+
+
+class NullTransport:
+ async def connect_tcp(self, host, port, timeout, local_address):
+ raise NotImplementedError
+
+
+class Backend: # pragma: no cover
+ def name(self):
+ return "unknown"
+
+ async def make_socket(
+ self,
+ af,
+ socktype,
+ proto=0,
+ source=None,
+ destination=None,
+ timeout=None,
+ ssl_context=None,
+ server_hostname=None,
+ ):
+ raise NotImplementedError
+
+ def datagram_connection_required(self):
+ return False
+
+ async def sleep(self, interval):
+ raise NotImplementedError
+
+ def get_transport_class(self):
+ raise NotImplementedError
+
+ async def wait_for(self, awaitable, timeout):
+ raise NotImplementedError
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_asyncio_backend.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_asyncio_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d9ed3690c6c84aa88102df63481dec1bf51d3d4
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_asyncio_backend.py
@@ -0,0 +1,275 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+"""asyncio library query support"""
+
+import asyncio
+import socket
+import sys
+
+import dns._asyncbackend
+import dns._features
+import dns.exception
+import dns.inet
+
+_is_win32 = sys.platform == "win32"
+
+
+def _get_running_loop():
+ try:
+ return asyncio.get_running_loop()
+ except AttributeError: # pragma: no cover
+ return asyncio.get_event_loop()
+
+
+class _DatagramProtocol:
+ def __init__(self):
+ self.transport = None
+ self.recvfrom = None
+
+ def connection_made(self, transport):
+ self.transport = transport
+
+ def datagram_received(self, data, addr):
+ if self.recvfrom and not self.recvfrom.done():
+ self.recvfrom.set_result((data, addr))
+
+ def error_received(self, exc): # pragma: no cover
+ if self.recvfrom and not self.recvfrom.done():
+ self.recvfrom.set_exception(exc)
+
+ def connection_lost(self, exc):
+ if self.recvfrom and not self.recvfrom.done():
+ if exc is None:
+ # EOF we triggered. Is there a better way to do this?
+ try:
+ raise EOFError
+ except EOFError as e:
+ self.recvfrom.set_exception(e)
+ else:
+ self.recvfrom.set_exception(exc)
+
+ def close(self):
+ self.transport.close()
+
+
+async def _maybe_wait_for(awaitable, timeout):
+ if timeout is not None:
+ try:
+ return await asyncio.wait_for(awaitable, timeout)
+ except asyncio.TimeoutError:
+ raise dns.exception.Timeout(timeout=timeout)
+ else:
+ return await awaitable
+
+
+class DatagramSocket(dns._asyncbackend.DatagramSocket):
+ def __init__(self, family, transport, protocol):
+ super().__init__(family)
+ self.transport = transport
+ self.protocol = protocol
+
+ async def sendto(self, what, destination, timeout): # pragma: no cover
+ # no timeout for asyncio sendto
+ self.transport.sendto(what, destination)
+ return len(what)
+
+ async def recvfrom(self, size, timeout):
+ # ignore size as there's no way I know to tell protocol about it
+ done = _get_running_loop().create_future()
+ try:
+ assert self.protocol.recvfrom is None
+ self.protocol.recvfrom = done
+ await _maybe_wait_for(done, timeout)
+ return done.result()
+ finally:
+ self.protocol.recvfrom = None
+
+ async def close(self):
+ self.protocol.close()
+
+ async def getpeername(self):
+ return self.transport.get_extra_info("peername")
+
+ async def getsockname(self):
+ return self.transport.get_extra_info("sockname")
+
+ async def getpeercert(self, timeout):
+ raise NotImplementedError
+
+
+class StreamSocket(dns._asyncbackend.StreamSocket):
+ def __init__(self, af, reader, writer):
+ self.family = af
+ self.reader = reader
+ self.writer = writer
+
+ async def sendall(self, what, timeout):
+ self.writer.write(what)
+ return await _maybe_wait_for(self.writer.drain(), timeout)
+
+ async def recv(self, size, timeout):
+ return await _maybe_wait_for(self.reader.read(size), timeout)
+
+ async def close(self):
+ self.writer.close()
+
+ async def getpeername(self):
+ return self.writer.get_extra_info("peername")
+
+ async def getsockname(self):
+ return self.writer.get_extra_info("sockname")
+
+ async def getpeercert(self, timeout):
+ return self.writer.get_extra_info("peercert")
+
+
+if dns._features.have("doh"):
+ import anyio
+ import httpcore
+ import httpcore._backends.anyio
+ import httpx
+
+ _CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend
+ _CoreAnyIOStream = httpcore._backends.anyio.AnyIOStream
+
+ from dns.query import _compute_times, _expiration_for_this_attempt, _remaining
+
+ class _NetworkBackend(_CoreAsyncNetworkBackend):
+ def __init__(self, resolver, local_port, bootstrap_address, family):
+ super().__init__()
+ self._local_port = local_port
+ self._resolver = resolver
+ self._bootstrap_address = bootstrap_address
+ self._family = family
+ if local_port != 0:
+ raise NotImplementedError(
+ "the asyncio transport for HTTPX cannot set the local port"
+ )
+
+ async def connect_tcp(
+ self, host, port, timeout, local_address, socket_options=None
+ ): # pylint: disable=signature-differs
+ addresses = []
+ _, expiration = _compute_times(timeout)
+ if dns.inet.is_address(host):
+ addresses.append(host)
+ elif self._bootstrap_address is not None:
+ addresses.append(self._bootstrap_address)
+ else:
+ timeout = _remaining(expiration)
+ family = self._family
+ if local_address:
+ family = dns.inet.af_for_address(local_address)
+ answers = await self._resolver.resolve_name(
+ host, family=family, lifetime=timeout
+ )
+ addresses = answers.addresses()
+ for address in addresses:
+ try:
+ attempt_expiration = _expiration_for_this_attempt(2.0, expiration)
+ timeout = _remaining(attempt_expiration)
+ with anyio.fail_after(timeout):
+ stream = await anyio.connect_tcp(
+ remote_host=address,
+ remote_port=port,
+ local_host=local_address,
+ )
+ return _CoreAnyIOStream(stream)
+ except Exception:
+ pass
+ raise httpcore.ConnectError
+
+ async def connect_unix_socket(
+ self, path, timeout, socket_options=None
+ ): # pylint: disable=signature-differs
+ raise NotImplementedError
+
+ async def sleep(self, seconds): # pylint: disable=signature-differs
+ await anyio.sleep(seconds)
+
+ class _HTTPTransport(httpx.AsyncHTTPTransport):
+ def __init__(
+ self,
+ *args,
+ local_port=0,
+ bootstrap_address=None,
+ resolver=None,
+ family=socket.AF_UNSPEC,
+ **kwargs,
+ ):
+ if resolver is None:
+ # pylint: disable=import-outside-toplevel,redefined-outer-name
+ import dns.asyncresolver
+
+ resolver = dns.asyncresolver.Resolver()
+ super().__init__(*args, **kwargs)
+ self._pool._network_backend = _NetworkBackend(
+ resolver, local_port, bootstrap_address, family
+ )
+
+else:
+ _HTTPTransport = dns._asyncbackend.NullTransport # type: ignore
+
+
+class Backend(dns._asyncbackend.Backend):
+ def name(self):
+ return "asyncio"
+
+ async def make_socket(
+ self,
+ af,
+ socktype,
+ proto=0,
+ source=None,
+ destination=None,
+ timeout=None,
+ ssl_context=None,
+ server_hostname=None,
+ ):
+ loop = _get_running_loop()
+ if socktype == socket.SOCK_DGRAM:
+ if _is_win32 and source is None:
+ # Win32 wants explicit binding before recvfrom(). This is the
+ # proper fix for [#637].
+ source = (dns.inet.any_for_af(af), 0)
+ transport, protocol = await loop.create_datagram_endpoint(
+ _DatagramProtocol,
+ source,
+ family=af,
+ proto=proto,
+ remote_addr=destination,
+ )
+ return DatagramSocket(af, transport, protocol)
+ elif socktype == socket.SOCK_STREAM:
+ if destination is None:
+ # This shouldn't happen, but we check to make code analysis software
+ # happier.
+ raise ValueError("destination required for stream sockets")
+ (r, w) = await _maybe_wait_for(
+ asyncio.open_connection(
+ destination[0],
+ destination[1],
+ ssl=ssl_context,
+ family=af,
+ proto=proto,
+ local_addr=source,
+ server_hostname=server_hostname,
+ ),
+ timeout,
+ )
+ return StreamSocket(af, r, w)
+ raise NotImplementedError(
+ "unsupported socket " + f"type {socktype}"
+ ) # pragma: no cover
+
+ async def sleep(self, interval):
+ await asyncio.sleep(interval)
+
+ def datagram_connection_required(self):
+ return False
+
+ def get_transport_class(self):
+ return _HTTPTransport
+
+ async def wait_for(self, awaitable, timeout):
+ return await _maybe_wait_for(awaitable, timeout)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_ddr.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_ddr.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf5c11eb6d98168766c5df3b2201e298388fa49e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_ddr.py
@@ -0,0 +1,154 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+#
+# Support for Discovery of Designated Resolvers
+
+import socket
+import time
+from urllib.parse import urlparse
+
+import dns.asyncbackend
+import dns.inet
+import dns.name
+import dns.nameserver
+import dns.query
+import dns.rdtypes.svcbbase
+
+# The special name of the local resolver when using DDR
+_local_resolver_name = dns.name.from_text("_dns.resolver.arpa")
+
+
+#
+# Processing is split up into I/O independent and I/O dependent parts to
+# make supporting sync and async versions easy.
+#
+
+
+class _SVCBInfo:
+ def __init__(self, bootstrap_address, port, hostname, nameservers):
+ self.bootstrap_address = bootstrap_address
+ self.port = port
+ self.hostname = hostname
+ self.nameservers = nameservers
+
+ def ddr_check_certificate(self, cert):
+ """Verify that the _SVCBInfo's address is in the cert's subjectAltName (SAN)"""
+ for name, value in cert["subjectAltName"]:
+ if name == "IP Address" and value == self.bootstrap_address:
+ return True
+ return False
+
+ def make_tls_context(self):
+ ssl = dns.query.ssl
+ ctx = ssl.create_default_context()
+ ctx.minimum_version = ssl.TLSVersion.TLSv1_2
+ return ctx
+
+ def ddr_tls_check_sync(self, lifetime):
+ ctx = self.make_tls_context()
+ expiration = time.time() + lifetime
+ with socket.create_connection(
+ (self.bootstrap_address, self.port), lifetime
+ ) as s:
+ with ctx.wrap_socket(s, server_hostname=self.hostname) as ts:
+ ts.settimeout(dns.query._remaining(expiration))
+ ts.do_handshake()
+ cert = ts.getpeercert()
+ return self.ddr_check_certificate(cert)
+
+ async def ddr_tls_check_async(self, lifetime, backend=None):
+ if backend is None:
+ backend = dns.asyncbackend.get_default_backend()
+ ctx = self.make_tls_context()
+ expiration = time.time() + lifetime
+ async with await backend.make_socket(
+ dns.inet.af_for_address(self.bootstrap_address),
+ socket.SOCK_STREAM,
+ 0,
+ None,
+ (self.bootstrap_address, self.port),
+ lifetime,
+ ctx,
+ self.hostname,
+ ) as ts:
+ cert = await ts.getpeercert(dns.query._remaining(expiration))
+ return self.ddr_check_certificate(cert)
+
+
+def _extract_nameservers_from_svcb(answer):
+ bootstrap_address = answer.nameserver
+ if not dns.inet.is_address(bootstrap_address):
+ return []
+ infos = []
+ for rr in answer.rrset.processing_order():
+ nameservers = []
+ param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.ALPN)
+ if param is None:
+ continue
+ alpns = set(param.ids)
+ host = rr.target.to_text(omit_final_dot=True)
+ port = None
+ param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.PORT)
+ if param is not None:
+ port = param.port
+ # For now we ignore address hints and address resolution and always use the
+ # bootstrap address
+ if b"h2" in alpns:
+ param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.DOHPATH)
+ if param is None or not param.value.endswith(b"{?dns}"):
+ continue
+ path = param.value[:-6].decode()
+ if not path.startswith("/"):
+ path = "/" + path
+ if port is None:
+ port = 443
+ url = f"https://{host}:{port}{path}"
+ # check the URL
+ try:
+ urlparse(url)
+ nameservers.append(dns.nameserver.DoHNameserver(url, bootstrap_address))
+ except Exception:
+ # continue processing other ALPN types
+ pass
+ if b"dot" in alpns:
+ if port is None:
+ port = 853
+ nameservers.append(
+ dns.nameserver.DoTNameserver(bootstrap_address, port, host)
+ )
+ if b"doq" in alpns:
+ if port is None:
+ port = 853
+ nameservers.append(
+ dns.nameserver.DoQNameserver(bootstrap_address, port, True, host)
+ )
+ if len(nameservers) > 0:
+ infos.append(_SVCBInfo(bootstrap_address, port, host, nameservers))
+ return infos
+
+
+def _get_nameservers_sync(answer, lifetime):
+ """Return a list of TLS-validated resolver nameservers extracted from an SVCB
+ answer."""
+ nameservers = []
+ infos = _extract_nameservers_from_svcb(answer)
+ for info in infos:
+ try:
+ if info.ddr_tls_check_sync(lifetime):
+ nameservers.extend(info.nameservers)
+ except Exception:
+ pass
+ return nameservers
+
+
+async def _get_nameservers_async(answer, lifetime):
+ """Return a list of TLS-validated resolver nameservers extracted from an SVCB
+ answer."""
+ nameservers = []
+ infos = _extract_nameservers_from_svcb(answer)
+ for info in infos:
+ try:
+ if await info.ddr_tls_check_async(lifetime):
+ nameservers.extend(info.nameservers)
+ except Exception:
+ pass
+ return nameservers
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_features.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_features.py
new file mode 100644
index 0000000000000000000000000000000000000000..03ccaa770431324d68b42ae13e21ac48abeb71dd
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_features.py
@@ -0,0 +1,92 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+import importlib.metadata
+import itertools
+import string
+from typing import Dict, List, Tuple
+
+
+def _tuple_from_text(version: str) -> Tuple:
+ text_parts = version.split(".")
+ int_parts = []
+ for text_part in text_parts:
+ digit_prefix = "".join(
+ itertools.takewhile(lambda x: x in string.digits, text_part)
+ )
+ try:
+ int_parts.append(int(digit_prefix))
+ except Exception:
+ break
+ return tuple(int_parts)
+
+
+def _version_check(
+ requirement: str,
+) -> bool:
+ """Is the requirement fulfilled?
+
+ The requirement must be of the form
+
+ package>=version
+ """
+ package, minimum = requirement.split(">=")
+ try:
+ version = importlib.metadata.version(package)
+ except Exception:
+ return False
+ t_version = _tuple_from_text(version)
+ t_minimum = _tuple_from_text(minimum)
+ if t_version < t_minimum:
+ return False
+ return True
+
+
+_cache: Dict[str, bool] = {}
+
+
+def have(feature: str) -> bool:
+ """Is *feature* available?
+
+ This tests if all optional packages needed for the
+ feature are available and recent enough.
+
+ Returns ``True`` if the feature is available,
+ and ``False`` if it is not or if metadata is
+ missing.
+ """
+ value = _cache.get(feature)
+ if value is not None:
+ return value
+ requirements = _requirements.get(feature)
+ if requirements is None:
+ # we make a cache entry here for consistency not performance
+ _cache[feature] = False
+ return False
+ ok = True
+ for requirement in requirements:
+ if not _version_check(requirement):
+ ok = False
+ break
+ _cache[feature] = ok
+ return ok
+
+
+def force(feature: str, enabled: bool) -> None:
+ """Force the status of *feature* to be *enabled*.
+
+ This method is provided as a workaround for any cases
+ where importlib.metadata is ineffective, or for testing.
+ """
+ _cache[feature] = enabled
+
+
+_requirements: Dict[str, List[str]] = {
+ ### BEGIN generated requirements
+ "dnssec": ["cryptography>=41"],
+ "doh": ["httpcore>=1.0.0", "httpx>=0.26.0", "h2>=4.1.0"],
+ "doq": ["aioquic>=0.9.25"],
+ "idna": ["idna>=3.6"],
+ "trio": ["trio>=0.23"],
+ "wmi": ["wmi>=1.5.1"],
+ ### END generated requirements
+}
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_immutable_ctx.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_immutable_ctx.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae7a33bf3a5f92252a5191b23086fd62e431e785
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_immutable_ctx.py
@@ -0,0 +1,76 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# This implementation of the immutable decorator requires python >=
+# 3.7, and is significantly more storage efficient when making classes
+# with slots immutable. It's also faster.
+
+import contextvars
+import inspect
+
+_in__init__ = contextvars.ContextVar("_immutable_in__init__", default=False)
+
+
+class _Immutable:
+ """Immutable mixin class"""
+
+ # We set slots to the empty list to say "we don't have any attributes".
+ # We do this so that if we're mixed in with a class with __slots__, we
+ # don't cause a __dict__ to be added which would waste space.
+
+ __slots__ = ()
+
+ def __setattr__(self, name, value):
+ if _in__init__.get() is not self:
+ raise TypeError("object doesn't support attribute assignment")
+ else:
+ super().__setattr__(name, value)
+
+ def __delattr__(self, name):
+ if _in__init__.get() is not self:
+ raise TypeError("object doesn't support attribute assignment")
+ else:
+ super().__delattr__(name)
+
+
+def _immutable_init(f):
+ def nf(*args, **kwargs):
+ previous = _in__init__.set(args[0])
+ try:
+ # call the actual __init__
+ f(*args, **kwargs)
+ finally:
+ _in__init__.reset(previous)
+
+ nf.__signature__ = inspect.signature(f)
+ return nf
+
+
+def immutable(cls):
+ if _Immutable in cls.__mro__:
+ # Some ancestor already has the mixin, so just make sure we keep
+ # following the __init__ protocol.
+ cls.__init__ = _immutable_init(cls.__init__)
+ if hasattr(cls, "__setstate__"):
+ cls.__setstate__ = _immutable_init(cls.__setstate__)
+ ncls = cls
+ else:
+ # Mixin the Immutable class and follow the __init__ protocol.
+ class ncls(_Immutable, cls):
+ # We have to do the __slots__ declaration here too!
+ __slots__ = ()
+
+ @_immutable_init
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ if hasattr(cls, "__setstate__"):
+
+ @_immutable_init
+ def __setstate__(self, *args, **kwargs):
+ super().__setstate__(*args, **kwargs)
+
+ # make ncls have the same name and module as cls
+ ncls.__name__ = cls.__name__
+ ncls.__qualname__ = cls.__qualname__
+ ncls.__module__ = cls.__module__
+ return ncls
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_trio_backend.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_trio_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..398e3276923bb6ae91d14a12de5d089cd134d7bb
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/_trio_backend.py
@@ -0,0 +1,250 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+"""trio async I/O library query support"""
+
+import socket
+
+import trio
+import trio.socket # type: ignore
+
+import dns._asyncbackend
+import dns._features
+import dns.exception
+import dns.inet
+
+if not dns._features.have("trio"):
+ raise ImportError("trio not found or too old")
+
+
+def _maybe_timeout(timeout):
+ if timeout is not None:
+ return trio.move_on_after(timeout)
+ else:
+ return dns._asyncbackend.NullContext()
+
+
+# for brevity
+_lltuple = dns.inet.low_level_address_tuple
+
+# pylint: disable=redefined-outer-name
+
+
+class DatagramSocket(dns._asyncbackend.DatagramSocket):
+ def __init__(self, socket):
+ super().__init__(socket.family)
+ self.socket = socket
+
+ async def sendto(self, what, destination, timeout):
+ with _maybe_timeout(timeout):
+ return await self.socket.sendto(what, destination)
+ raise dns.exception.Timeout(
+ timeout=timeout
+ ) # pragma: no cover lgtm[py/unreachable-statement]
+
+ async def recvfrom(self, size, timeout):
+ with _maybe_timeout(timeout):
+ return await self.socket.recvfrom(size)
+ raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement]
+
+ async def close(self):
+ self.socket.close()
+
+ async def getpeername(self):
+ return self.socket.getpeername()
+
+ async def getsockname(self):
+ return self.socket.getsockname()
+
+ async def getpeercert(self, timeout):
+ raise NotImplementedError
+
+
+class StreamSocket(dns._asyncbackend.StreamSocket):
+ def __init__(self, family, stream, tls=False):
+ self.family = family
+ self.stream = stream
+ self.tls = tls
+
+ async def sendall(self, what, timeout):
+ with _maybe_timeout(timeout):
+ return await self.stream.send_all(what)
+ raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement]
+
+ async def recv(self, size, timeout):
+ with _maybe_timeout(timeout):
+ return await self.stream.receive_some(size)
+ raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement]
+
+ async def close(self):
+ await self.stream.aclose()
+
+ async def getpeername(self):
+ if self.tls:
+ return self.stream.transport_stream.socket.getpeername()
+ else:
+ return self.stream.socket.getpeername()
+
+ async def getsockname(self):
+ if self.tls:
+ return self.stream.transport_stream.socket.getsockname()
+ else:
+ return self.stream.socket.getsockname()
+
+ async def getpeercert(self, timeout):
+ if self.tls:
+ with _maybe_timeout(timeout):
+ await self.stream.do_handshake()
+ return self.stream.getpeercert()
+ else:
+ raise NotImplementedError
+
+
+if dns._features.have("doh"):
+ import httpcore
+ import httpcore._backends.trio
+ import httpx
+
+ _CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend
+ _CoreTrioStream = httpcore._backends.trio.TrioStream
+
+ from dns.query import _compute_times, _expiration_for_this_attempt, _remaining
+
+ class _NetworkBackend(_CoreAsyncNetworkBackend):
+ def __init__(self, resolver, local_port, bootstrap_address, family):
+ super().__init__()
+ self._local_port = local_port
+ self._resolver = resolver
+ self._bootstrap_address = bootstrap_address
+ self._family = family
+
+ async def connect_tcp(
+ self, host, port, timeout, local_address, socket_options=None
+ ): # pylint: disable=signature-differs
+ addresses = []
+ _, expiration = _compute_times(timeout)
+ if dns.inet.is_address(host):
+ addresses.append(host)
+ elif self._bootstrap_address is not None:
+ addresses.append(self._bootstrap_address)
+ else:
+ timeout = _remaining(expiration)
+ family = self._family
+ if local_address:
+ family = dns.inet.af_for_address(local_address)
+ answers = await self._resolver.resolve_name(
+ host, family=family, lifetime=timeout
+ )
+ addresses = answers.addresses()
+ for address in addresses:
+ try:
+ af = dns.inet.af_for_address(address)
+ if local_address is not None or self._local_port != 0:
+ source = (local_address, self._local_port)
+ else:
+ source = None
+ destination = (address, port)
+ attempt_expiration = _expiration_for_this_attempt(2.0, expiration)
+ timeout = _remaining(attempt_expiration)
+ sock = await Backend().make_socket(
+ af, socket.SOCK_STREAM, 0, source, destination, timeout
+ )
+ return _CoreTrioStream(sock.stream)
+ except Exception:
+ continue
+ raise httpcore.ConnectError
+
+ async def connect_unix_socket(
+ self, path, timeout, socket_options=None
+ ): # pylint: disable=signature-differs
+ raise NotImplementedError
+
+ async def sleep(self, seconds): # pylint: disable=signature-differs
+ await trio.sleep(seconds)
+
+ class _HTTPTransport(httpx.AsyncHTTPTransport):
+ def __init__(
+ self,
+ *args,
+ local_port=0,
+ bootstrap_address=None,
+ resolver=None,
+ family=socket.AF_UNSPEC,
+ **kwargs,
+ ):
+ if resolver is None:
+ # pylint: disable=import-outside-toplevel,redefined-outer-name
+ import dns.asyncresolver
+
+ resolver = dns.asyncresolver.Resolver()
+ super().__init__(*args, **kwargs)
+ self._pool._network_backend = _NetworkBackend(
+ resolver, local_port, bootstrap_address, family
+ )
+
+else:
+ _HTTPTransport = dns._asyncbackend.NullTransport # type: ignore
+
+
+class Backend(dns._asyncbackend.Backend):
+ def name(self):
+ return "trio"
+
+ async def make_socket(
+ self,
+ af,
+ socktype,
+ proto=0,
+ source=None,
+ destination=None,
+ timeout=None,
+ ssl_context=None,
+ server_hostname=None,
+ ):
+ s = trio.socket.socket(af, socktype, proto)
+ stream = None
+ try:
+ if source:
+ await s.bind(_lltuple(source, af))
+ if socktype == socket.SOCK_STREAM:
+ connected = False
+ with _maybe_timeout(timeout):
+ await s.connect(_lltuple(destination, af))
+ connected = True
+ if not connected:
+ raise dns.exception.Timeout(
+ timeout=timeout
+ ) # lgtm[py/unreachable-statement]
+ except Exception: # pragma: no cover
+ s.close()
+ raise
+ if socktype == socket.SOCK_DGRAM:
+ return DatagramSocket(s)
+ elif socktype == socket.SOCK_STREAM:
+ stream = trio.SocketStream(s)
+ tls = False
+ if ssl_context:
+ tls = True
+ try:
+ stream = trio.SSLStream(
+ stream, ssl_context, server_hostname=server_hostname
+ )
+ except Exception: # pragma: no cover
+ await stream.aclose()
+ raise
+ return StreamSocket(af, stream, tls)
+ raise NotImplementedError(
+ "unsupported socket " + f"type {socktype}"
+ ) # pragma: no cover
+
+ async def sleep(self, interval):
+ await trio.sleep(interval)
+
+ def get_transport_class(self):
+ return _HTTPTransport
+
+ async def wait_for(self, awaitable, timeout):
+ with _maybe_timeout(timeout):
+ return await awaitable
+ raise dns.exception.Timeout(
+ timeout=timeout
+ ) # pragma: no cover lgtm[py/unreachable-statement]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncbackend.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncbackend.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ec58b062a149500ce89783cfc812a5b46e5f263
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncbackend.py
@@ -0,0 +1,101 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+from typing import Dict
+
+import dns.exception
+
+# pylint: disable=unused-import
+from dns._asyncbackend import ( # noqa: F401 lgtm[py/unused-import]
+ Backend,
+ DatagramSocket,
+ Socket,
+ StreamSocket,
+)
+
+# pylint: enable=unused-import
+
+_default_backend = None
+
+_backends: Dict[str, Backend] = {}
+
+# Allow sniffio import to be disabled for testing purposes
+_no_sniffio = False
+
+
+class AsyncLibraryNotFoundError(dns.exception.DNSException):
+ pass
+
+
+def get_backend(name: str) -> Backend:
+ """Get the specified asynchronous backend.
+
+ *name*, a ``str``, the name of the backend. Currently the "trio"
+ and "asyncio" backends are available.
+
+ Raises NotImplementedError if an unknown backend name is specified.
+ """
+ # pylint: disable=import-outside-toplevel,redefined-outer-name
+ backend = _backends.get(name)
+ if backend:
+ return backend
+ if name == "trio":
+ import dns._trio_backend
+
+ backend = dns._trio_backend.Backend()
+ elif name == "asyncio":
+ import dns._asyncio_backend
+
+ backend = dns._asyncio_backend.Backend()
+ else:
+ raise NotImplementedError(f"unimplemented async backend {name}")
+ _backends[name] = backend
+ return backend
+
+
+def sniff() -> str:
+ """Attempt to determine the in-use asynchronous I/O library by using
+ the ``sniffio`` module if it is available.
+
+ Returns the name of the library, or raises AsyncLibraryNotFoundError
+ if the library cannot be determined.
+ """
+ # pylint: disable=import-outside-toplevel
+ try:
+ if _no_sniffio:
+ raise ImportError
+ import sniffio
+
+ try:
+ return sniffio.current_async_library()
+ except sniffio.AsyncLibraryNotFoundError:
+ raise AsyncLibraryNotFoundError("sniffio cannot determine async library")
+ except ImportError:
+ import asyncio
+
+ try:
+ asyncio.get_running_loop()
+ return "asyncio"
+ except RuntimeError:
+ raise AsyncLibraryNotFoundError("no async library detected")
+
+
+def get_default_backend() -> Backend:
+ """Get the default backend, initializing it if necessary."""
+ if _default_backend:
+ return _default_backend
+
+ return set_default_backend(sniff())
+
+
+def set_default_backend(name: str) -> Backend:
+ """Set the default backend.
+
+ It's not normally necessary to call this method, as
+ ``get_default_backend()`` will initialize the backend
+ appropriately in many cases. If ``sniffio`` is not installed, or
+ in testing situations, this function allows the backend to be set
+ explicitly.
+ """
+ global _default_backend
+ _default_backend = get_backend(name)
+ return _default_backend
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncquery.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncquery.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d9ab9ae49385e83515143ced8a04b01938fcab1
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncquery.py
@@ -0,0 +1,780 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Talk to a DNS server."""
+
+import base64
+import contextlib
+import socket
+import struct
+import time
+from typing import Any, Dict, Optional, Tuple, Union
+
+import dns.asyncbackend
+import dns.exception
+import dns.inet
+import dns.message
+import dns.name
+import dns.quic
+import dns.rcode
+import dns.rdataclass
+import dns.rdatatype
+import dns.transaction
+from dns._asyncbackend import NullContext
+from dns.query import (
+ BadResponse,
+ NoDOH,
+ NoDOQ,
+ UDPMode,
+ _compute_times,
+ _make_dot_ssl_context,
+ _matches_destination,
+ _remaining,
+ have_doh,
+ ssl,
+)
+
+if have_doh:
+ import httpx
+
+# for brevity
+_lltuple = dns.inet.low_level_address_tuple
+
+
+def _source_tuple(af, address, port):
+ # Make a high level source tuple, or return None if address and port
+ # are both None
+ if address or port:
+ if address is None:
+ if af == socket.AF_INET:
+ address = "0.0.0.0"
+ elif af == socket.AF_INET6:
+ address = "::"
+ else:
+ raise NotImplementedError(f"unknown address family {af}")
+ return (address, port)
+ else:
+ return None
+
+
+def _timeout(expiration, now=None):
+ if expiration is not None:
+ if not now:
+ now = time.time()
+ return max(expiration - now, 0)
+ else:
+ return None
+
+
+async def send_udp(
+ sock: dns.asyncbackend.DatagramSocket,
+ what: Union[dns.message.Message, bytes],
+ destination: Any,
+ expiration: Optional[float] = None,
+) -> Tuple[int, float]:
+ """Send a DNS message to the specified UDP socket.
+
+ *sock*, a ``dns.asyncbackend.DatagramSocket``.
+
+ *what*, a ``bytes`` or ``dns.message.Message``, the message to send.
+
+ *destination*, a destination tuple appropriate for the address family
+ of the socket, specifying where to send the query.
+
+ *expiration*, a ``float`` or ``None``, the absolute time at which
+ a timeout exception should be raised. If ``None``, no timeout will
+ occur. The expiration value is meaningless for the asyncio backend, as
+ asyncio's transport sendto() never blocks.
+
+ Returns an ``(int, float)`` tuple of bytes sent and the sent time.
+ """
+
+ if isinstance(what, dns.message.Message):
+ what = what.to_wire()
+ sent_time = time.time()
+ n = await sock.sendto(what, destination, _timeout(expiration, sent_time))
+ return (n, sent_time)
+
+
+async def receive_udp(
+ sock: dns.asyncbackend.DatagramSocket,
+ destination: Optional[Any] = None,
+ expiration: Optional[float] = None,
+ ignore_unexpected: bool = False,
+ one_rr_per_rrset: bool = False,
+ keyring: Optional[Dict[dns.name.Name, dns.tsig.Key]] = None,
+ request_mac: Optional[bytes] = b"",
+ ignore_trailing: bool = False,
+ raise_on_truncation: bool = False,
+ ignore_errors: bool = False,
+ query: Optional[dns.message.Message] = None,
+) -> Any:
+ """Read a DNS message from a UDP socket.
+
+ *sock*, a ``dns.asyncbackend.DatagramSocket``.
+
+ See :py:func:`dns.query.receive_udp()` for the documentation of the other
+ parameters, and exceptions.
+
+ Returns a ``(dns.message.Message, float, tuple)`` tuple of the received message, the
+ received time, and the address where the message arrived from.
+ """
+
+ wire = b""
+ while True:
+ (wire, from_address) = await sock.recvfrom(65535, _timeout(expiration))
+ if not _matches_destination(
+ sock.family, from_address, destination, ignore_unexpected
+ ):
+ continue
+ received_time = time.time()
+ try:
+ r = dns.message.from_wire(
+ wire,
+ keyring=keyring,
+ request_mac=request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ raise_on_truncation=raise_on_truncation,
+ )
+ except dns.message.Truncated as e:
+ # See the comment in query.py for details.
+ if (
+ ignore_errors
+ and query is not None
+ and not query.is_response(e.message())
+ ):
+ continue
+ else:
+ raise
+ except Exception:
+ if ignore_errors:
+ continue
+ else:
+ raise
+ if ignore_errors and query is not None and not query.is_response(r):
+ continue
+ return (r, received_time, from_address)
+
+
+async def udp(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 53,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ ignore_unexpected: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ raise_on_truncation: bool = False,
+ sock: Optional[dns.asyncbackend.DatagramSocket] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+ ignore_errors: bool = False,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via UDP.
+
+ *sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``,
+ the socket to use for the query. If ``None``, the default, a
+ socket is created. Note that if a socket is provided, the
+ *source*, *source_port*, and *backend* are ignored.
+
+ *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
+ the default, then dnspython will use the default backend.
+
+ See :py:func:`dns.query.udp()` for the documentation of the other
+ parameters, exceptions, and return type of this method.
+ """
+ wire = q.to_wire()
+ (begin_time, expiration) = _compute_times(timeout)
+ af = dns.inet.af_for_address(where)
+ destination = _lltuple((where, port), af)
+ if sock:
+ cm: contextlib.AbstractAsyncContextManager = NullContext(sock)
+ else:
+ if not backend:
+ backend = dns.asyncbackend.get_default_backend()
+ stuple = _source_tuple(af, source, source_port)
+ if backend.datagram_connection_required():
+ dtuple = (where, port)
+ else:
+ dtuple = None
+ cm = await backend.make_socket(af, socket.SOCK_DGRAM, 0, stuple, dtuple)
+ async with cm as s:
+ await send_udp(s, wire, destination, expiration)
+ (r, received_time, _) = await receive_udp(
+ s,
+ destination,
+ expiration,
+ ignore_unexpected,
+ one_rr_per_rrset,
+ q.keyring,
+ q.mac,
+ ignore_trailing,
+ raise_on_truncation,
+ ignore_errors,
+ q,
+ )
+ r.time = received_time - begin_time
+ # We don't need to check q.is_response() if we are in ignore_errors mode
+ # as receive_udp() will have checked it.
+ if not (ignore_errors or q.is_response(r)):
+ raise BadResponse
+ return r
+
+
+async def udp_with_fallback(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 53,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ ignore_unexpected: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ udp_sock: Optional[dns.asyncbackend.DatagramSocket] = None,
+ tcp_sock: Optional[dns.asyncbackend.StreamSocket] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+ ignore_errors: bool = False,
+) -> Tuple[dns.message.Message, bool]:
+ """Return the response to the query, trying UDP first and falling back
+ to TCP if UDP results in a truncated response.
+
+ *udp_sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``,
+ the socket to use for the UDP query. If ``None``, the default, a
+ socket is created. Note that if a socket is provided the *source*,
+ *source_port*, and *backend* are ignored for the UDP query.
+
+ *tcp_sock*, a ``dns.asyncbackend.StreamSocket``, or ``None``, the
+ socket to use for the TCP query. If ``None``, the default, a
+ socket is created. Note that if a socket is provided *where*,
+ *source*, *source_port*, and *backend* are ignored for the TCP query.
+
+ *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
+ the default, then dnspython will use the default backend.
+
+ See :py:func:`dns.query.udp_with_fallback()` for the documentation
+ of the other parameters, exceptions, and return type of this
+ method.
+ """
+ try:
+ response = await udp(
+ q,
+ where,
+ timeout,
+ port,
+ source,
+ source_port,
+ ignore_unexpected,
+ one_rr_per_rrset,
+ ignore_trailing,
+ True,
+ udp_sock,
+ backend,
+ ignore_errors,
+ )
+ return (response, False)
+ except dns.message.Truncated:
+ response = await tcp(
+ q,
+ where,
+ timeout,
+ port,
+ source,
+ source_port,
+ one_rr_per_rrset,
+ ignore_trailing,
+ tcp_sock,
+ backend,
+ )
+ return (response, True)
+
+
+async def send_tcp(
+ sock: dns.asyncbackend.StreamSocket,
+ what: Union[dns.message.Message, bytes],
+ expiration: Optional[float] = None,
+) -> Tuple[int, float]:
+ """Send a DNS message to the specified TCP socket.
+
+ *sock*, a ``dns.asyncbackend.StreamSocket``.
+
+ See :py:func:`dns.query.send_tcp()` for the documentation of the other
+ parameters, exceptions, and return type of this method.
+ """
+
+ if isinstance(what, dns.message.Message):
+ tcpmsg = what.to_wire(prepend_length=True)
+ else:
+ # copying the wire into tcpmsg is inefficient, but lets us
+ # avoid writev() or doing a short write that would get pushed
+ # onto the net
+ tcpmsg = len(what).to_bytes(2, "big") + what
+ sent_time = time.time()
+ await sock.sendall(tcpmsg, _timeout(expiration, sent_time))
+ return (len(tcpmsg), sent_time)
+
+
+async def _read_exactly(sock, count, expiration):
+ """Read the specified number of bytes from stream. Keep trying until we
+ either get the desired amount, or we hit EOF.
+ """
+ s = b""
+ while count > 0:
+ n = await sock.recv(count, _timeout(expiration))
+ if n == b"":
+ raise EOFError
+ count = count - len(n)
+ s = s + n
+ return s
+
+
+async def receive_tcp(
+ sock: dns.asyncbackend.StreamSocket,
+ expiration: Optional[float] = None,
+ one_rr_per_rrset: bool = False,
+ keyring: Optional[Dict[dns.name.Name, dns.tsig.Key]] = None,
+ request_mac: Optional[bytes] = b"",
+ ignore_trailing: bool = False,
+) -> Tuple[dns.message.Message, float]:
+ """Read a DNS message from a TCP socket.
+
+ *sock*, a ``dns.asyncbackend.StreamSocket``.
+
+ See :py:func:`dns.query.receive_tcp()` for the documentation of the other
+ parameters, exceptions, and return type of this method.
+ """
+
+ ldata = await _read_exactly(sock, 2, expiration)
+ (l,) = struct.unpack("!H", ldata)
+ wire = await _read_exactly(sock, l, expiration)
+ received_time = time.time()
+ r = dns.message.from_wire(
+ wire,
+ keyring=keyring,
+ request_mac=request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ return (r, received_time)
+
+
+async def tcp(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 53,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ sock: Optional[dns.asyncbackend.StreamSocket] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via TCP.
+
+ *sock*, a ``dns.asyncbacket.StreamSocket``, or ``None``, the
+ socket to use for the query. If ``None``, the default, a socket
+ is created. Note that if a socket is provided
+ *where*, *port*, *source*, *source_port*, and *backend* are ignored.
+
+ *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
+ the default, then dnspython will use the default backend.
+
+ See :py:func:`dns.query.tcp()` for the documentation of the other
+ parameters, exceptions, and return type of this method.
+ """
+
+ wire = q.to_wire()
+ (begin_time, expiration) = _compute_times(timeout)
+ if sock:
+ # Verify that the socket is connected, as if it's not connected,
+ # it's not writable, and the polling in send_tcp() will time out or
+ # hang forever.
+ await sock.getpeername()
+ cm: contextlib.AbstractAsyncContextManager = NullContext(sock)
+ else:
+ # These are simple (address, port) pairs, not family-dependent tuples
+ # you pass to low-level socket code.
+ af = dns.inet.af_for_address(where)
+ stuple = _source_tuple(af, source, source_port)
+ dtuple = (where, port)
+ if not backend:
+ backend = dns.asyncbackend.get_default_backend()
+ cm = await backend.make_socket(
+ af, socket.SOCK_STREAM, 0, stuple, dtuple, timeout
+ )
+ async with cm as s:
+ await send_tcp(s, wire, expiration)
+ (r, received_time) = await receive_tcp(
+ s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing
+ )
+ r.time = received_time - begin_time
+ if not q.is_response(r):
+ raise BadResponse
+ return r
+
+
+async def tls(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 853,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ sock: Optional[dns.asyncbackend.StreamSocket] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+ ssl_context: Optional[ssl.SSLContext] = None,
+ server_hostname: Optional[str] = None,
+ verify: Union[bool, str] = True,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via TLS.
+
+ *sock*, an ``asyncbackend.StreamSocket``, or ``None``, the socket
+ to use for the query. If ``None``, the default, a socket is
+ created. Note that if a socket is provided, it must be a
+ connected SSL stream socket, and *where*, *port*,
+ *source*, *source_port*, *backend*, *ssl_context*, and *server_hostname*
+ are ignored.
+
+ *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
+ the default, then dnspython will use the default backend.
+
+ See :py:func:`dns.query.tls()` for the documentation of the other
+ parameters, exceptions, and return type of this method.
+ """
+ (begin_time, expiration) = _compute_times(timeout)
+ if sock:
+ cm: contextlib.AbstractAsyncContextManager = NullContext(sock)
+ else:
+ if ssl_context is None:
+ ssl_context = _make_dot_ssl_context(server_hostname, verify)
+ af = dns.inet.af_for_address(where)
+ stuple = _source_tuple(af, source, source_port)
+ dtuple = (where, port)
+ if not backend:
+ backend = dns.asyncbackend.get_default_backend()
+ cm = await backend.make_socket(
+ af,
+ socket.SOCK_STREAM,
+ 0,
+ stuple,
+ dtuple,
+ timeout,
+ ssl_context,
+ server_hostname,
+ )
+ async with cm as s:
+ timeout = _timeout(expiration)
+ response = await tcp(
+ q,
+ where,
+ timeout,
+ port,
+ source,
+ source_port,
+ one_rr_per_rrset,
+ ignore_trailing,
+ s,
+ backend,
+ )
+ end_time = time.time()
+ response.time = end_time - begin_time
+ return response
+
+
+async def https(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 443,
+ source: Optional[str] = None,
+ source_port: int = 0, # pylint: disable=W0613
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ client: Optional["httpx.AsyncClient"] = None,
+ path: str = "/dns-query",
+ post: bool = True,
+ verify: Union[bool, str] = True,
+ bootstrap_address: Optional[str] = None,
+ resolver: Optional["dns.asyncresolver.Resolver"] = None,
+ family: Optional[int] = socket.AF_UNSPEC,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via DNS-over-HTTPS.
+
+ *client*, a ``httpx.AsyncClient``. If provided, the client to use for
+ the query.
+
+ Unlike the other dnspython async functions, a backend cannot be provided
+ in this function because httpx always auto-detects the async backend.
+
+ See :py:func:`dns.query.https()` for the documentation of the other
+ parameters, exceptions, and return type of this method.
+ """
+
+ if not have_doh:
+ raise NoDOH # pragma: no cover
+ if client and not isinstance(client, httpx.AsyncClient):
+ raise ValueError("session parameter must be an httpx.AsyncClient")
+
+ wire = q.to_wire()
+ try:
+ af = dns.inet.af_for_address(where)
+ except ValueError:
+ af = None
+ transport = None
+ headers = {"accept": "application/dns-message"}
+ if af is not None and dns.inet.is_address(where):
+ if af == socket.AF_INET:
+ url = "https://{}:{}{}".format(where, port, path)
+ elif af == socket.AF_INET6:
+ url = "https://[{}]:{}{}".format(where, port, path)
+ else:
+ url = where
+
+ backend = dns.asyncbackend.get_default_backend()
+
+ if source is None:
+ local_address = None
+ local_port = 0
+ else:
+ local_address = source
+ local_port = source_port
+ transport = backend.get_transport_class()(
+ local_address=local_address,
+ http1=True,
+ http2=True,
+ verify=verify,
+ local_port=local_port,
+ bootstrap_address=bootstrap_address,
+ resolver=resolver,
+ family=family,
+ )
+
+ if client:
+ cm: contextlib.AbstractAsyncContextManager = NullContext(client)
+ else:
+ cm = httpx.AsyncClient(
+ http1=True, http2=True, verify=verify, transport=transport
+ )
+
+ async with cm as the_client:
+ # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH
+ # GET and POST examples
+ if post:
+ headers.update(
+ {
+ "content-type": "application/dns-message",
+ "content-length": str(len(wire)),
+ }
+ )
+ response = await backend.wait_for(
+ the_client.post(url, headers=headers, content=wire), timeout
+ )
+ else:
+ wire = base64.urlsafe_b64encode(wire).rstrip(b"=")
+ twire = wire.decode() # httpx does a repr() if we give it bytes
+ response = await backend.wait_for(
+ the_client.get(url, headers=headers, params={"dns": twire}), timeout
+ )
+
+ # see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH
+ # status codes
+ if response.status_code < 200 or response.status_code > 299:
+ raise ValueError(
+ "{} responded with status code {}"
+ "\nResponse body: {!r}".format(
+ where, response.status_code, response.content
+ )
+ )
+ r = dns.message.from_wire(
+ response.content,
+ keyring=q.keyring,
+ request_mac=q.request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ r.time = response.elapsed.total_seconds()
+ if not q.is_response(r):
+ raise BadResponse
+ return r
+
+
+async def inbound_xfr(
+ where: str,
+ txn_manager: dns.transaction.TransactionManager,
+ query: Optional[dns.message.Message] = None,
+ port: int = 53,
+ timeout: Optional[float] = None,
+ lifetime: Optional[float] = None,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ udp_mode: UDPMode = UDPMode.NEVER,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+) -> None:
+ """Conduct an inbound transfer and apply it via a transaction from the
+ txn_manager.
+
+ *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
+ the default, then dnspython will use the default backend.
+
+ See :py:func:`dns.query.inbound_xfr()` for the documentation of
+ the other parameters, exceptions, and return type of this method.
+ """
+ if query is None:
+ (query, serial) = dns.xfr.make_query(txn_manager)
+ else:
+ serial = dns.xfr.extract_serial_from_query(query)
+ rdtype = query.question[0].rdtype
+ is_ixfr = rdtype == dns.rdatatype.IXFR
+ origin = txn_manager.from_wire_origin()
+ wire = query.to_wire()
+ af = dns.inet.af_for_address(where)
+ stuple = _source_tuple(af, source, source_port)
+ dtuple = (where, port)
+ (_, expiration) = _compute_times(lifetime)
+ retry = True
+ while retry:
+ retry = False
+ if is_ixfr and udp_mode != UDPMode.NEVER:
+ sock_type = socket.SOCK_DGRAM
+ is_udp = True
+ else:
+ sock_type = socket.SOCK_STREAM
+ is_udp = False
+ if not backend:
+ backend = dns.asyncbackend.get_default_backend()
+ s = await backend.make_socket(
+ af, sock_type, 0, stuple, dtuple, _timeout(expiration)
+ )
+ async with s:
+ if is_udp:
+ await s.sendto(wire, dtuple, _timeout(expiration))
+ else:
+ tcpmsg = struct.pack("!H", len(wire)) + wire
+ await s.sendall(tcpmsg, expiration)
+ with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound:
+ done = False
+ tsig_ctx = None
+ while not done:
+ (_, mexpiration) = _compute_times(timeout)
+ if mexpiration is None or (
+ expiration is not None and mexpiration > expiration
+ ):
+ mexpiration = expiration
+ if is_udp:
+ destination = _lltuple((where, port), af)
+ while True:
+ timeout = _timeout(mexpiration)
+ (rwire, from_address) = await s.recvfrom(65535, timeout)
+ if _matches_destination(
+ af, from_address, destination, True
+ ):
+ break
+ else:
+ ldata = await _read_exactly(s, 2, mexpiration)
+ (l,) = struct.unpack("!H", ldata)
+ rwire = await _read_exactly(s, l, mexpiration)
+ is_ixfr = rdtype == dns.rdatatype.IXFR
+ r = dns.message.from_wire(
+ rwire,
+ keyring=query.keyring,
+ request_mac=query.mac,
+ xfr=True,
+ origin=origin,
+ tsig_ctx=tsig_ctx,
+ multi=(not is_udp),
+ one_rr_per_rrset=is_ixfr,
+ )
+ try:
+ done = inbound.process_message(r)
+ except dns.xfr.UseTCP:
+ assert is_udp # should not happen if we used TCP!
+ if udp_mode == UDPMode.ONLY:
+ raise
+ done = True
+ retry = True
+ udp_mode = UDPMode.NEVER
+ continue
+ tsig_ctx = r.tsig_ctx
+ if not retry and query.keyring and not r.had_tsig:
+ raise dns.exception.FormError("missing TSIG")
+
+
+async def quic(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 853,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ connection: Optional[dns.quic.AsyncQuicConnection] = None,
+ verify: Union[bool, str] = True,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+ server_hostname: Optional[str] = None,
+) -> dns.message.Message:
+ """Return the response obtained after sending an asynchronous query via
+ DNS-over-QUIC.
+
+ *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
+ the default, then dnspython will use the default backend.
+
+ See :py:func:`dns.query.quic()` for the documentation of the other
+ parameters, exceptions, and return type of this method.
+ """
+
+ if not dns.quic.have_quic:
+ raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover
+
+ q.id = 0
+ wire = q.to_wire()
+ the_connection: dns.quic.AsyncQuicConnection
+ if connection:
+ cfactory = dns.quic.null_factory
+ mfactory = dns.quic.null_factory
+ the_connection = connection
+ else:
+ (cfactory, mfactory) = dns.quic.factories_for_backend(backend)
+
+ async with cfactory() as context:
+ async with mfactory(
+ context, verify_mode=verify, server_name=server_hostname
+ ) as the_manager:
+ if not connection:
+ the_connection = the_manager.connect(where, port, source, source_port)
+ (start, expiration) = _compute_times(timeout)
+ stream = await the_connection.make_stream(timeout)
+ async with stream:
+ await stream.send(wire, True)
+ wire = await stream.receive(_remaining(expiration))
+ finish = time.time()
+ r = dns.message.from_wire(
+ wire,
+ keyring=q.keyring,
+ request_mac=q.request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ r.time = max(finish - start, 0.0)
+ if not q.is_response(r):
+ raise BadResponse
+ return r
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncresolver.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncresolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f5e062a9ee5c1bf19acf363da7344b8d393e32a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/asyncresolver.py
@@ -0,0 +1,475 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Asynchronous DNS stub resolver."""
+
+import socket
+import time
+from typing import Any, Dict, List, Optional, Union
+
+import dns._ddr
+import dns.asyncbackend
+import dns.asyncquery
+import dns.exception
+import dns.name
+import dns.query
+import dns.rdataclass
+import dns.rdatatype
+import dns.resolver # lgtm[py/import-and-import-from]
+
+# import some resolver symbols for brevity
+from dns.resolver import NXDOMAIN, NoAnswer, NoRootSOA, NotAbsolute
+
+# for indentation purposes below
+_udp = dns.asyncquery.udp
+_tcp = dns.asyncquery.tcp
+
+
+class Resolver(dns.resolver.BaseResolver):
+ """Asynchronous DNS stub resolver."""
+
+ async def resolve(
+ self,
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+ search: Optional[bool] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+ ) -> dns.resolver.Answer:
+ """Query nameservers asynchronously to find the answer to the question.
+
+ *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
+ the default, then dnspython will use the default backend.
+
+ See :py:func:`dns.resolver.Resolver.resolve()` for the
+ documentation of the other parameters, exceptions, and return
+ type of this method.
+ """
+
+ resolution = dns.resolver._Resolution(
+ self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search
+ )
+ if not backend:
+ backend = dns.asyncbackend.get_default_backend()
+ start = time.time()
+ while True:
+ (request, answer) = resolution.next_request()
+ # Note we need to say "if answer is not None" and not just
+ # "if answer" because answer implements __len__, and python
+ # will call that. We want to return if we have an answer
+ # object, including in cases where its length is 0.
+ if answer is not None:
+ # cache hit!
+ return answer
+ assert request is not None # needed for type checking
+ done = False
+ while not done:
+ (nameserver, tcp, backoff) = resolution.next_nameserver()
+ if backoff:
+ await backend.sleep(backoff)
+ timeout = self._compute_timeout(start, lifetime, resolution.errors)
+ try:
+ response = await nameserver.async_query(
+ request,
+ timeout=timeout,
+ source=source,
+ source_port=source_port,
+ max_size=tcp,
+ backend=backend,
+ )
+ except Exception as ex:
+ (_, done) = resolution.query_result(None, ex)
+ continue
+ (answer, done) = resolution.query_result(response, None)
+ # Note we need to say "if answer is not None" and not just
+ # "if answer" because answer implements __len__, and python
+ # will call that. We want to return if we have an answer
+ # object, including in cases where its length is 0.
+ if answer is not None:
+ return answer
+
+ async def resolve_address(
+ self, ipaddr: str, *args: Any, **kwargs: Any
+ ) -> dns.resolver.Answer:
+ """Use an asynchronous resolver to run a reverse query for PTR
+ records.
+
+ This utilizes the resolve() method to perform a PTR lookup on the
+ specified IP address.
+
+ *ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get
+ the PTR record for.
+
+ All other arguments that can be passed to the resolve() function
+ except for rdtype and rdclass are also supported by this
+ function.
+
+ """
+ # We make a modified kwargs for type checking happiness, as otherwise
+ # we get a legit warning about possibly having rdtype and rdclass
+ # in the kwargs more than once.
+ modified_kwargs: Dict[str, Any] = {}
+ modified_kwargs.update(kwargs)
+ modified_kwargs["rdtype"] = dns.rdatatype.PTR
+ modified_kwargs["rdclass"] = dns.rdataclass.IN
+ return await self.resolve(
+ dns.reversename.from_address(ipaddr), *args, **modified_kwargs
+ )
+
+ async def resolve_name(
+ self,
+ name: Union[dns.name.Name, str],
+ family: int = socket.AF_UNSPEC,
+ **kwargs: Any,
+ ) -> dns.resolver.HostAnswers:
+ """Use an asynchronous resolver to query for address records.
+
+ This utilizes the resolve() method to perform A and/or AAAA lookups on
+ the specified name.
+
+ *qname*, a ``dns.name.Name`` or ``str``, the name to resolve.
+
+ *family*, an ``int``, the address family. If socket.AF_UNSPEC
+ (the default), both A and AAAA records will be retrieved.
+
+ All other arguments that can be passed to the resolve() function
+ except for rdtype and rdclass are also supported by this
+ function.
+ """
+ # We make a modified kwargs for type checking happiness, as otherwise
+ # we get a legit warning about possibly having rdtype and rdclass
+ # in the kwargs more than once.
+ modified_kwargs: Dict[str, Any] = {}
+ modified_kwargs.update(kwargs)
+ modified_kwargs.pop("rdtype", None)
+ modified_kwargs["rdclass"] = dns.rdataclass.IN
+
+ if family == socket.AF_INET:
+ v4 = await self.resolve(name, dns.rdatatype.A, **modified_kwargs)
+ return dns.resolver.HostAnswers.make(v4=v4)
+ elif family == socket.AF_INET6:
+ v6 = await self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs)
+ return dns.resolver.HostAnswers.make(v6=v6)
+ elif family != socket.AF_UNSPEC:
+ raise NotImplementedError(f"unknown address family {family}")
+
+ raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True)
+ lifetime = modified_kwargs.pop("lifetime", None)
+ start = time.time()
+ v6 = await self.resolve(
+ name,
+ dns.rdatatype.AAAA,
+ raise_on_no_answer=False,
+ lifetime=self._compute_timeout(start, lifetime),
+ **modified_kwargs,
+ )
+ # Note that setting name ensures we query the same name
+ # for A as we did for AAAA. (This is just in case search lists
+ # are active by default in the resolver configuration and
+ # we might be talking to a server that says NXDOMAIN when it
+ # wants to say NOERROR no data.
+ name = v6.qname
+ v4 = await self.resolve(
+ name,
+ dns.rdatatype.A,
+ raise_on_no_answer=False,
+ lifetime=self._compute_timeout(start, lifetime),
+ **modified_kwargs,
+ )
+ answers = dns.resolver.HostAnswers.make(
+ v6=v6, v4=v4, add_empty=not raise_on_no_answer
+ )
+ if not answers:
+ raise NoAnswer(response=v6.response)
+ return answers
+
+ # pylint: disable=redefined-outer-name
+
+ async def canonical_name(self, name: Union[dns.name.Name, str]) -> dns.name.Name:
+ """Determine the canonical name of *name*.
+
+ The canonical name is the name the resolver uses for queries
+ after all CNAME and DNAME renamings have been applied.
+
+ *name*, a ``dns.name.Name`` or ``str``, the query name.
+
+ This method can raise any exception that ``resolve()`` can
+ raise, other than ``dns.resolver.NoAnswer`` and
+ ``dns.resolver.NXDOMAIN``.
+
+ Returns a ``dns.name.Name``.
+ """
+ try:
+ answer = await self.resolve(name, raise_on_no_answer=False)
+ canonical_name = answer.canonical_name
+ except dns.resolver.NXDOMAIN as e:
+ canonical_name = e.canonical_name
+ return canonical_name
+
+ async def try_ddr(self, lifetime: float = 5.0) -> None:
+ """Try to update the resolver's nameservers using Discovery of Designated
+ Resolvers (DDR). If successful, the resolver will subsequently use
+ DNS-over-HTTPS or DNS-over-TLS for future queries.
+
+ *lifetime*, a float, is the maximum time to spend attempting DDR. The default
+ is 5 seconds.
+
+ If the SVCB query is successful and results in a non-empty list of nameservers,
+ then the resolver's nameservers are set to the returned servers in priority
+ order.
+
+ The current implementation does not use any address hints from the SVCB record,
+ nor does it resolve addresses for the SCVB target name, rather it assumes that
+ the bootstrap nameserver will always be one of the addresses and uses it.
+ A future revision to the code may offer fuller support. The code verifies that
+ the bootstrap nameserver is in the Subject Alternative Name field of the
+ TLS certficate.
+ """
+ try:
+ expiration = time.time() + lifetime
+ answer = await self.resolve(
+ dns._ddr._local_resolver_name, "svcb", lifetime=lifetime
+ )
+ timeout = dns.query._remaining(expiration)
+ nameservers = await dns._ddr._get_nameservers_async(answer, timeout)
+ if len(nameservers) > 0:
+ self.nameservers = nameservers
+ except Exception:
+ pass
+
+
+default_resolver = None
+
+
+def get_default_resolver() -> Resolver:
+ """Get the default asynchronous resolver, initializing it if necessary."""
+ if default_resolver is None:
+ reset_default_resolver()
+ assert default_resolver is not None
+ return default_resolver
+
+
+def reset_default_resolver() -> None:
+ """Re-initialize default asynchronous resolver.
+
+ Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX
+ systems) will be re-read immediately.
+ """
+
+ global default_resolver
+ default_resolver = Resolver()
+
+
+async def resolve(
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+ search: Optional[bool] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+) -> dns.resolver.Answer:
+ """Query nameservers asynchronously to find the answer to the question.
+
+ This is a convenience function that uses the default resolver
+ object to make the query.
+
+ See :py:func:`dns.asyncresolver.Resolver.resolve` for more
+ information on the parameters.
+ """
+
+ return await get_default_resolver().resolve(
+ qname,
+ rdtype,
+ rdclass,
+ tcp,
+ source,
+ raise_on_no_answer,
+ source_port,
+ lifetime,
+ search,
+ backend,
+ )
+
+
+async def resolve_address(
+ ipaddr: str, *args: Any, **kwargs: Any
+) -> dns.resolver.Answer:
+ """Use a resolver to run a reverse query for PTR records.
+
+ See :py:func:`dns.asyncresolver.Resolver.resolve_address` for more
+ information on the parameters.
+ """
+
+ return await get_default_resolver().resolve_address(ipaddr, *args, **kwargs)
+
+
+async def resolve_name(
+ name: Union[dns.name.Name, str], family: int = socket.AF_UNSPEC, **kwargs: Any
+) -> dns.resolver.HostAnswers:
+ """Use a resolver to asynchronously query for address records.
+
+ See :py:func:`dns.asyncresolver.Resolver.resolve_name` for more
+ information on the parameters.
+ """
+
+ return await get_default_resolver().resolve_name(name, family, **kwargs)
+
+
+async def canonical_name(name: Union[dns.name.Name, str]) -> dns.name.Name:
+ """Determine the canonical name of *name*.
+
+ See :py:func:`dns.resolver.Resolver.canonical_name` for more
+ information on the parameters and possible exceptions.
+ """
+
+ return await get_default_resolver().canonical_name(name)
+
+
+async def try_ddr(timeout: float = 5.0) -> None:
+ """Try to update the default resolver's nameservers using Discovery of Designated
+ Resolvers (DDR). If successful, the resolver will subsequently use
+ DNS-over-HTTPS or DNS-over-TLS for future queries.
+
+ See :py:func:`dns.resolver.Resolver.try_ddr` for more information.
+ """
+ return await get_default_resolver().try_ddr(timeout)
+
+
+async def zone_for_name(
+ name: Union[dns.name.Name, str],
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ tcp: bool = False,
+ resolver: Optional[Resolver] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+) -> dns.name.Name:
+ """Find the name of the zone which contains the specified name.
+
+ See :py:func:`dns.resolver.Resolver.zone_for_name` for more
+ information on the parameters and possible exceptions.
+ """
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, dns.name.root)
+ if resolver is None:
+ resolver = get_default_resolver()
+ if not name.is_absolute():
+ raise NotAbsolute(name)
+ while True:
+ try:
+ answer = await resolver.resolve(
+ name, dns.rdatatype.SOA, rdclass, tcp, backend=backend
+ )
+ assert answer.rrset is not None
+ if answer.rrset.name == name:
+ return name
+ # otherwise we were CNAMEd or DNAMEd and need to look higher
+ except (NXDOMAIN, NoAnswer):
+ pass
+ try:
+ name = name.parent()
+ except dns.name.NoParent: # pragma: no cover
+ raise NoRootSOA
+
+
+async def make_resolver_at(
+ where: Union[dns.name.Name, str],
+ port: int = 53,
+ family: int = socket.AF_UNSPEC,
+ resolver: Optional[Resolver] = None,
+) -> Resolver:
+ """Make a stub resolver using the specified destination as the full resolver.
+
+ *where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the
+ full resolver.
+
+ *port*, an ``int``, the port to use. If not specified, the default is 53.
+
+ *family*, an ``int``, the address family to use. This parameter is used if
+ *where* is not an address. The default is ``socket.AF_UNSPEC`` in which case
+ the first address returned by ``resolve_name()`` will be used, otherwise the
+ first address of the specified family will be used.
+
+ *resolver*, a ``dns.asyncresolver.Resolver`` or ``None``, the resolver to use for
+ resolution of hostnames. If not specified, the default resolver will be used.
+
+ Returns a ``dns.resolver.Resolver`` or raises an exception.
+ """
+ if resolver is None:
+ resolver = get_default_resolver()
+ nameservers: List[Union[str, dns.nameserver.Nameserver]] = []
+ if isinstance(where, str) and dns.inet.is_address(where):
+ nameservers.append(dns.nameserver.Do53Nameserver(where, port))
+ else:
+ answers = await resolver.resolve_name(where, family)
+ for address in answers.addresses():
+ nameservers.append(dns.nameserver.Do53Nameserver(address, port))
+ res = dns.asyncresolver.Resolver(configure=False)
+ res.nameservers = nameservers
+ return res
+
+
+async def resolve_at(
+ where: Union[dns.name.Name, str],
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+ search: Optional[bool] = None,
+ backend: Optional[dns.asyncbackend.Backend] = None,
+ port: int = 53,
+ family: int = socket.AF_UNSPEC,
+ resolver: Optional[Resolver] = None,
+) -> dns.resolver.Answer:
+ """Query nameservers to find the answer to the question.
+
+ This is a convenience function that calls ``dns.asyncresolver.make_resolver_at()``
+ to make a resolver, and then uses it to resolve the query.
+
+ See ``dns.asyncresolver.Resolver.resolve`` for more information on the resolution
+ parameters, and ``dns.asyncresolver.make_resolver_at`` for information about the
+ resolver parameters *where*, *port*, *family*, and *resolver*.
+
+ If making more than one query, it is more efficient to call
+ ``dns.asyncresolver.make_resolver_at()`` and then use that resolver for the queries
+ instead of calling ``resolve_at()`` multiple times.
+ """
+ res = await make_resolver_at(where, port, family, resolver)
+ return await res.resolve(
+ qname,
+ rdtype,
+ rdclass,
+ tcp,
+ source,
+ raise_on_no_answer,
+ source_port,
+ lifetime,
+ search,
+ backend,
+ )
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/dnssec.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/dnssec.py
new file mode 100644
index 0000000000000000000000000000000000000000..e49c3b795b5108486700e79e6c4ea7c534adcebf
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/dnssec.py
@@ -0,0 +1,1223 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Common DNSSEC-related functions and constants."""
+
+
+import base64
+import contextlib
+import functools
+import hashlib
+import struct
+import time
+from datetime import datetime
+from typing import Callable, Dict, List, Optional, Set, Tuple, Union, cast
+
+import dns._features
+import dns.exception
+import dns.name
+import dns.node
+import dns.rdata
+import dns.rdataclass
+import dns.rdataset
+import dns.rdatatype
+import dns.rrset
+import dns.transaction
+import dns.zone
+from dns.dnssectypes import Algorithm, DSDigest, NSEC3Hash
+from dns.exception import ( # pylint: disable=W0611
+ AlgorithmKeyMismatch,
+ DeniedByPolicy,
+ UnsupportedAlgorithm,
+ ValidationFailure,
+)
+from dns.rdtypes.ANY.CDNSKEY import CDNSKEY
+from dns.rdtypes.ANY.CDS import CDS
+from dns.rdtypes.ANY.DNSKEY import DNSKEY
+from dns.rdtypes.ANY.DS import DS
+from dns.rdtypes.ANY.NSEC import NSEC, Bitmap
+from dns.rdtypes.ANY.NSEC3PARAM import NSEC3PARAM
+from dns.rdtypes.ANY.RRSIG import RRSIG, sigtime_to_posixtime
+from dns.rdtypes.dnskeybase import Flag
+
+PublicKey = Union[
+ "GenericPublicKey",
+ "rsa.RSAPublicKey",
+ "ec.EllipticCurvePublicKey",
+ "ed25519.Ed25519PublicKey",
+ "ed448.Ed448PublicKey",
+]
+
+PrivateKey = Union[
+ "GenericPrivateKey",
+ "rsa.RSAPrivateKey",
+ "ec.EllipticCurvePrivateKey",
+ "ed25519.Ed25519PrivateKey",
+ "ed448.Ed448PrivateKey",
+]
+
+RRsetSigner = Callable[[dns.transaction.Transaction, dns.rrset.RRset], None]
+
+
+def algorithm_from_text(text: str) -> Algorithm:
+ """Convert text into a DNSSEC algorithm value.
+
+ *text*, a ``str``, the text to convert to into an algorithm value.
+
+ Returns an ``int``.
+ """
+
+ return Algorithm.from_text(text)
+
+
+def algorithm_to_text(value: Union[Algorithm, int]) -> str:
+ """Convert a DNSSEC algorithm value to text
+
+ *value*, a ``dns.dnssec.Algorithm``.
+
+ Returns a ``str``, the name of a DNSSEC algorithm.
+ """
+
+ return Algorithm.to_text(value)
+
+
+def to_timestamp(value: Union[datetime, str, float, int]) -> int:
+ """Convert various format to a timestamp"""
+ if isinstance(value, datetime):
+ return int(value.timestamp())
+ elif isinstance(value, str):
+ return sigtime_to_posixtime(value)
+ elif isinstance(value, float):
+ return int(value)
+ elif isinstance(value, int):
+ return value
+ else:
+ raise TypeError("Unsupported timestamp type")
+
+
+def key_id(key: Union[DNSKEY, CDNSKEY]) -> int:
+ """Return the key id (a 16-bit number) for the specified key.
+
+ *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY``
+
+ Returns an ``int`` between 0 and 65535
+ """
+
+ rdata = key.to_wire()
+ if key.algorithm == Algorithm.RSAMD5:
+ return (rdata[-3] << 8) + rdata[-2]
+ else:
+ total = 0
+ for i in range(len(rdata) // 2):
+ total += (rdata[2 * i] << 8) + rdata[2 * i + 1]
+ if len(rdata) % 2 != 0:
+ total += rdata[len(rdata) - 1] << 8
+ total += (total >> 16) & 0xFFFF
+ return total & 0xFFFF
+
+
+class Policy:
+ def __init__(self):
+ pass
+
+ def ok_to_sign(self, _: DNSKEY) -> bool: # pragma: no cover
+ return False
+
+ def ok_to_validate(self, _: DNSKEY) -> bool: # pragma: no cover
+ return False
+
+ def ok_to_create_ds(self, _: DSDigest) -> bool: # pragma: no cover
+ return False
+
+ def ok_to_validate_ds(self, _: DSDigest) -> bool: # pragma: no cover
+ return False
+
+
+class SimpleDeny(Policy):
+ def __init__(self, deny_sign, deny_validate, deny_create_ds, deny_validate_ds):
+ super().__init__()
+ self._deny_sign = deny_sign
+ self._deny_validate = deny_validate
+ self._deny_create_ds = deny_create_ds
+ self._deny_validate_ds = deny_validate_ds
+
+ def ok_to_sign(self, key: DNSKEY) -> bool:
+ return key.algorithm not in self._deny_sign
+
+ def ok_to_validate(self, key: DNSKEY) -> bool:
+ return key.algorithm not in self._deny_validate
+
+ def ok_to_create_ds(self, algorithm: DSDigest) -> bool:
+ return algorithm not in self._deny_create_ds
+
+ def ok_to_validate_ds(self, algorithm: DSDigest) -> bool:
+ return algorithm not in self._deny_validate_ds
+
+
+rfc_8624_policy = SimpleDeny(
+ {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1, Algorithm.ECCGOST},
+ {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1},
+ {DSDigest.NULL, DSDigest.SHA1, DSDigest.GOST},
+ {DSDigest.NULL},
+)
+
+allow_all_policy = SimpleDeny(set(), set(), set(), set())
+
+
+default_policy = rfc_8624_policy
+
+
+def make_ds(
+ name: Union[dns.name.Name, str],
+ key: dns.rdata.Rdata,
+ algorithm: Union[DSDigest, str],
+ origin: Optional[dns.name.Name] = None,
+ policy: Optional[Policy] = None,
+ validating: bool = False,
+) -> DS:
+ """Create a DS record for a DNSSEC key.
+
+ *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record.
+
+ *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``,
+ the key the DS is about.
+
+ *algorithm*, a ``str`` or ``int`` specifying the hash algorithm.
+ The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
+ does not matter for these strings.
+
+ *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name,
+ then it will be made absolute using the specified origin.
+
+ *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
+ ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
+
+ *validating*, a ``bool``. If ``True``, then policy is checked in
+ validating mode, i.e. "Is it ok to validate using this digest algorithm?".
+ Otherwise the policy is checked in creating mode, i.e. "Is it ok to create a DS with
+ this digest algorithm?".
+
+ Raises ``UnsupportedAlgorithm`` if the algorithm is unknown.
+
+ Raises ``DeniedByPolicy`` if the algorithm is denied by policy.
+
+ Returns a ``dns.rdtypes.ANY.DS.DS``
+ """
+
+ if policy is None:
+ policy = default_policy
+ try:
+ if isinstance(algorithm, str):
+ algorithm = DSDigest[algorithm.upper()]
+ except Exception:
+ raise UnsupportedAlgorithm('unsupported algorithm "%s"' % algorithm)
+ if validating:
+ check = policy.ok_to_validate_ds
+ else:
+ check = policy.ok_to_create_ds
+ if not check(algorithm):
+ raise DeniedByPolicy
+ if not isinstance(key, (DNSKEY, CDNSKEY)):
+ raise ValueError("key is not a DNSKEY/CDNSKEY")
+ if algorithm == DSDigest.SHA1:
+ dshash = hashlib.sha1()
+ elif algorithm == DSDigest.SHA256:
+ dshash = hashlib.sha256()
+ elif algorithm == DSDigest.SHA384:
+ dshash = hashlib.sha384()
+ else:
+ raise UnsupportedAlgorithm('unsupported algorithm "%s"' % algorithm)
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, origin)
+ wire = name.canonicalize().to_wire()
+ assert wire is not None
+ dshash.update(wire)
+ dshash.update(key.to_wire(origin=origin))
+ digest = dshash.digest()
+
+ dsrdata = struct.pack("!HBB", key_id(key), key.algorithm, algorithm) + digest
+ ds = dns.rdata.from_wire(
+ dns.rdataclass.IN, dns.rdatatype.DS, dsrdata, 0, len(dsrdata)
+ )
+ return cast(DS, ds)
+
+
+def make_cds(
+ name: Union[dns.name.Name, str],
+ key: dns.rdata.Rdata,
+ algorithm: Union[DSDigest, str],
+ origin: Optional[dns.name.Name] = None,
+) -> CDS:
+ """Create a CDS record for a DNSSEC key.
+
+ *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record.
+
+ *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``,
+ the key the DS is about.
+
+ *algorithm*, a ``str`` or ``int`` specifying the hash algorithm.
+ The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
+ does not matter for these strings.
+
+ *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name,
+ then it will be made absolute using the specified origin.
+
+ Raises ``UnsupportedAlgorithm`` if the algorithm is unknown.
+
+ Returns a ``dns.rdtypes.ANY.DS.CDS``
+ """
+
+ ds = make_ds(name, key, algorithm, origin)
+ return CDS(
+ rdclass=ds.rdclass,
+ rdtype=dns.rdatatype.CDS,
+ key_tag=ds.key_tag,
+ algorithm=ds.algorithm,
+ digest_type=ds.digest_type,
+ digest=ds.digest,
+ )
+
+
+def _find_candidate_keys(
+ keys: Dict[dns.name.Name, Union[dns.rdataset.Rdataset, dns.node.Node]], rrsig: RRSIG
+) -> Optional[List[DNSKEY]]:
+ value = keys.get(rrsig.signer)
+ if isinstance(value, dns.node.Node):
+ rdataset = value.get_rdataset(dns.rdataclass.IN, dns.rdatatype.DNSKEY)
+ else:
+ rdataset = value
+ if rdataset is None:
+ return None
+ return [
+ cast(DNSKEY, rd)
+ for rd in rdataset
+ if rd.algorithm == rrsig.algorithm
+ and key_id(rd) == rrsig.key_tag
+ and (rd.flags & Flag.ZONE) == Flag.ZONE # RFC 4034 2.1.1
+ and rd.protocol == 3 # RFC 4034 2.1.2
+ ]
+
+
+def _get_rrname_rdataset(
+ rrset: Union[dns.rrset.RRset, Tuple[dns.name.Name, dns.rdataset.Rdataset]],
+) -> Tuple[dns.name.Name, dns.rdataset.Rdataset]:
+ if isinstance(rrset, tuple):
+ return rrset[0], rrset[1]
+ else:
+ return rrset.name, rrset
+
+
+def _validate_signature(sig: bytes, data: bytes, key: DNSKEY) -> None:
+ public_cls = get_algorithm_cls_from_dnskey(key).public_cls
+ try:
+ public_key = public_cls.from_dnskey(key)
+ except ValueError:
+ raise ValidationFailure("invalid public key")
+ public_key.verify(sig, data)
+
+
+def _validate_rrsig(
+ rrset: Union[dns.rrset.RRset, Tuple[dns.name.Name, dns.rdataset.Rdataset]],
+ rrsig: RRSIG,
+ keys: Dict[dns.name.Name, Union[dns.node.Node, dns.rdataset.Rdataset]],
+ origin: Optional[dns.name.Name] = None,
+ now: Optional[float] = None,
+ policy: Optional[Policy] = None,
+) -> None:
+ """Validate an RRset against a single signature rdata, throwing an
+ exception if validation is not successful.
+
+ *rrset*, the RRset to validate. This can be a
+ ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
+ tuple.
+
+ *rrsig*, a ``dns.rdata.Rdata``, the signature to validate.
+
+ *keys*, the key dictionary, used to find the DNSKEY associated
+ with a given name. The dictionary is keyed by a
+ ``dns.name.Name``, and has ``dns.node.Node`` or
+ ``dns.rdataset.Rdataset`` values.
+
+ *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative
+ names.
+
+ *now*, a ``float`` or ``None``, the time, in seconds since the epoch, to
+ use as the current time when validating. If ``None``, the actual current
+ time is used.
+
+ *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
+ ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
+
+ Raises ``ValidationFailure`` if the signature is expired, not yet valid,
+ the public key is invalid, the algorithm is unknown, the verification
+ fails, etc.
+
+ Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by
+ dnspython but not implemented.
+ """
+
+ if policy is None:
+ policy = default_policy
+
+ candidate_keys = _find_candidate_keys(keys, rrsig)
+ if candidate_keys is None:
+ raise ValidationFailure("unknown key")
+
+ if now is None:
+ now = time.time()
+ if rrsig.expiration < now:
+ raise ValidationFailure("expired")
+ if rrsig.inception > now:
+ raise ValidationFailure("not yet valid")
+
+ data = _make_rrsig_signature_data(rrset, rrsig, origin)
+
+ for candidate_key in candidate_keys:
+ if not policy.ok_to_validate(candidate_key):
+ continue
+ try:
+ _validate_signature(rrsig.signature, data, candidate_key)
+ return
+ except (InvalidSignature, ValidationFailure):
+ # this happens on an individual validation failure
+ continue
+ # nothing verified -- raise failure:
+ raise ValidationFailure("verify failure")
+
+
+def _validate(
+ rrset: Union[dns.rrset.RRset, Tuple[dns.name.Name, dns.rdataset.Rdataset]],
+ rrsigset: Union[dns.rrset.RRset, Tuple[dns.name.Name, dns.rdataset.Rdataset]],
+ keys: Dict[dns.name.Name, Union[dns.node.Node, dns.rdataset.Rdataset]],
+ origin: Optional[dns.name.Name] = None,
+ now: Optional[float] = None,
+ policy: Optional[Policy] = None,
+) -> None:
+ """Validate an RRset against a signature RRset, throwing an exception
+ if none of the signatures validate.
+
+ *rrset*, the RRset to validate. This can be a
+ ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
+ tuple.
+
+ *rrsigset*, the signature RRset. This can be a
+ ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
+ tuple.
+
+ *keys*, the key dictionary, used to find the DNSKEY associated
+ with a given name. The dictionary is keyed by a
+ ``dns.name.Name``, and has ``dns.node.Node`` or
+ ``dns.rdataset.Rdataset`` values.
+
+ *origin*, a ``dns.name.Name``, the origin to use for relative names;
+ defaults to None.
+
+ *now*, an ``int`` or ``None``, the time, in seconds since the epoch, to
+ use as the current time when validating. If ``None``, the actual current
+ time is used.
+
+ *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
+ ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
+
+ Raises ``ValidationFailure`` if the signature is expired, not yet valid,
+ the public key is invalid, the algorithm is unknown, the verification
+ fails, etc.
+ """
+
+ if policy is None:
+ policy = default_policy
+
+ if isinstance(origin, str):
+ origin = dns.name.from_text(origin, dns.name.root)
+
+ if isinstance(rrset, tuple):
+ rrname = rrset[0]
+ else:
+ rrname = rrset.name
+
+ if isinstance(rrsigset, tuple):
+ rrsigname = rrsigset[0]
+ rrsigrdataset = rrsigset[1]
+ else:
+ rrsigname = rrsigset.name
+ rrsigrdataset = rrsigset
+
+ rrname = rrname.choose_relativity(origin)
+ rrsigname = rrsigname.choose_relativity(origin)
+ if rrname != rrsigname:
+ raise ValidationFailure("owner names do not match")
+
+ for rrsig in rrsigrdataset:
+ if not isinstance(rrsig, RRSIG):
+ raise ValidationFailure("expected an RRSIG")
+ try:
+ _validate_rrsig(rrset, rrsig, keys, origin, now, policy)
+ return
+ except (ValidationFailure, UnsupportedAlgorithm):
+ pass
+ raise ValidationFailure("no RRSIGs validated")
+
+
+def _sign(
+ rrset: Union[dns.rrset.RRset, Tuple[dns.name.Name, dns.rdataset.Rdataset]],
+ private_key: PrivateKey,
+ signer: dns.name.Name,
+ dnskey: DNSKEY,
+ inception: Optional[Union[datetime, str, int, float]] = None,
+ expiration: Optional[Union[datetime, str, int, float]] = None,
+ lifetime: Optional[int] = None,
+ verify: bool = False,
+ policy: Optional[Policy] = None,
+ origin: Optional[dns.name.Name] = None,
+) -> RRSIG:
+ """Sign RRset using private key.
+
+ *rrset*, the RRset to validate. This can be a
+ ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
+ tuple.
+
+ *private_key*, the private key to use for signing, a
+ ``cryptography.hazmat.primitives.asymmetric`` private key class applicable
+ for DNSSEC.
+
+ *signer*, a ``dns.name.Name``, the Signer's name.
+
+ *dnskey*, a ``DNSKEY`` matching ``private_key``.
+
+ *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the
+ signature inception time. If ``None``, the current time is used. If a ``str``, the
+ format is "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX
+ epoch in text form; this is the same the RRSIG rdata's text form.
+ Values of type `int` or `float` are interpreted as seconds since the UNIX epoch.
+
+ *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature
+ expiration time. If ``None``, the expiration time will be the inception time plus
+ the value of the *lifetime* parameter. See the description of *inception* above
+ for how the various parameter types are interpreted.
+
+ *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This
+ parameter is only meaningful if *expiration* is ``None``.
+
+ *verify*, a ``bool``. If set to ``True``, the signer will verify signatures
+ after they are created; the default is ``False``.
+
+ *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
+ ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
+
+ *origin*, a ``dns.name.Name`` or ``None``. If ``None``, the default, then all
+ names in the rrset (including its owner name) must be absolute; otherwise the
+ specified origin will be used to make names absolute when signing.
+
+ Raises ``DeniedByPolicy`` if the signature is denied by policy.
+ """
+
+ if policy is None:
+ policy = default_policy
+ if not policy.ok_to_sign(dnskey):
+ raise DeniedByPolicy
+
+ if isinstance(rrset, tuple):
+ rdclass = rrset[1].rdclass
+ rdtype = rrset[1].rdtype
+ rrname = rrset[0]
+ original_ttl = rrset[1].ttl
+ else:
+ rdclass = rrset.rdclass
+ rdtype = rrset.rdtype
+ rrname = rrset.name
+ original_ttl = rrset.ttl
+
+ if inception is not None:
+ rrsig_inception = to_timestamp(inception)
+ else:
+ rrsig_inception = int(time.time())
+
+ if expiration is not None:
+ rrsig_expiration = to_timestamp(expiration)
+ elif lifetime is not None:
+ rrsig_expiration = rrsig_inception + lifetime
+ else:
+ raise ValueError("expiration or lifetime must be specified")
+
+ # Derelativize now because we need a correct labels length for the
+ # rrsig_template.
+ if origin is not None:
+ rrname = rrname.derelativize(origin)
+ labels = len(rrname) - 1
+
+ # Adjust labels appropriately for wildcards.
+ if rrname.is_wild():
+ labels -= 1
+
+ rrsig_template = RRSIG(
+ rdclass=rdclass,
+ rdtype=dns.rdatatype.RRSIG,
+ type_covered=rdtype,
+ algorithm=dnskey.algorithm,
+ labels=labels,
+ original_ttl=original_ttl,
+ expiration=rrsig_expiration,
+ inception=rrsig_inception,
+ key_tag=key_id(dnskey),
+ signer=signer,
+ signature=b"",
+ )
+
+ data = dns.dnssec._make_rrsig_signature_data(rrset, rrsig_template, origin)
+
+ if isinstance(private_key, GenericPrivateKey):
+ signing_key = private_key
+ else:
+ try:
+ private_cls = get_algorithm_cls_from_dnskey(dnskey)
+ signing_key = private_cls(key=private_key)
+ except UnsupportedAlgorithm:
+ raise TypeError("Unsupported key algorithm")
+
+ signature = signing_key.sign(data, verify)
+
+ return cast(RRSIG, rrsig_template.replace(signature=signature))
+
+
+def _make_rrsig_signature_data(
+ rrset: Union[dns.rrset.RRset, Tuple[dns.name.Name, dns.rdataset.Rdataset]],
+ rrsig: RRSIG,
+ origin: Optional[dns.name.Name] = None,
+) -> bytes:
+ """Create signature rdata.
+
+ *rrset*, the RRset to sign/validate. This can be a
+ ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
+ tuple.
+
+ *rrsig*, a ``dns.rdata.Rdata``, the signature to validate, or the
+ signature template used when signing.
+
+ *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative
+ names.
+
+ Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by
+ dnspython but not implemented.
+ """
+
+ if isinstance(origin, str):
+ origin = dns.name.from_text(origin, dns.name.root)
+
+ signer = rrsig.signer
+ if not signer.is_absolute():
+ if origin is None:
+ raise ValidationFailure("relative RR name without an origin specified")
+ signer = signer.derelativize(origin)
+
+ # For convenience, allow the rrset to be specified as a (name,
+ # rdataset) tuple as well as a proper rrset
+ rrname, rdataset = _get_rrname_rdataset(rrset)
+
+ data = b""
+ data += rrsig.to_wire(origin=signer)[:18]
+ data += rrsig.signer.to_digestable(signer)
+
+ # Derelativize the name before considering labels.
+ if not rrname.is_absolute():
+ if origin is None:
+ raise ValidationFailure("relative RR name without an origin specified")
+ rrname = rrname.derelativize(origin)
+
+ name_len = len(rrname)
+ if rrname.is_wild() and rrsig.labels != name_len - 2:
+ raise ValidationFailure("wild owner name has wrong label length")
+ if name_len - 1 < rrsig.labels:
+ raise ValidationFailure("owner name longer than RRSIG labels")
+ elif rrsig.labels < name_len - 1:
+ suffix = rrname.split(rrsig.labels + 1)[1]
+ rrname = dns.name.from_text("*", suffix)
+ rrnamebuf = rrname.to_digestable()
+ rrfixed = struct.pack("!HHI", rdataset.rdtype, rdataset.rdclass, rrsig.original_ttl)
+ rdatas = [rdata.to_digestable(origin) for rdata in rdataset]
+ for rdata in sorted(rdatas):
+ data += rrnamebuf
+ data += rrfixed
+ rrlen = struct.pack("!H", len(rdata))
+ data += rrlen
+ data += rdata
+
+ return data
+
+
+def _make_dnskey(
+ public_key: PublicKey,
+ algorithm: Union[int, str],
+ flags: int = Flag.ZONE,
+ protocol: int = 3,
+) -> DNSKEY:
+ """Convert a public key to DNSKEY Rdata
+
+ *public_key*, a ``PublicKey`` (``GenericPublicKey`` or
+ ``cryptography.hazmat.primitives.asymmetric``) to convert.
+
+ *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm.
+
+ *flags*: DNSKEY flags field as an integer.
+
+ *protocol*: DNSKEY protocol field as an integer.
+
+ Raises ``ValueError`` if the specified key algorithm parameters are not
+ unsupported, ``TypeError`` if the key type is unsupported,
+ `UnsupportedAlgorithm` if the algorithm is unknown and
+ `AlgorithmKeyMismatch` if the algorithm does not match the key type.
+
+ Return DNSKEY ``Rdata``.
+ """
+
+ algorithm = Algorithm.make(algorithm)
+
+ if isinstance(public_key, GenericPublicKey):
+ return public_key.to_dnskey(flags=flags, protocol=protocol)
+ else:
+ public_cls = get_algorithm_cls(algorithm).public_cls
+ return public_cls(key=public_key).to_dnskey(flags=flags, protocol=protocol)
+
+
+def _make_cdnskey(
+ public_key: PublicKey,
+ algorithm: Union[int, str],
+ flags: int = Flag.ZONE,
+ protocol: int = 3,
+) -> CDNSKEY:
+ """Convert a public key to CDNSKEY Rdata
+
+ *public_key*, the public key to convert, a
+ ``cryptography.hazmat.primitives.asymmetric`` public key class applicable
+ for DNSSEC.
+
+ *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm.
+
+ *flags*: DNSKEY flags field as an integer.
+
+ *protocol*: DNSKEY protocol field as an integer.
+
+ Raises ``ValueError`` if the specified key algorithm parameters are not
+ unsupported, ``TypeError`` if the key type is unsupported,
+ `UnsupportedAlgorithm` if the algorithm is unknown and
+ `AlgorithmKeyMismatch` if the algorithm does not match the key type.
+
+ Return CDNSKEY ``Rdata``.
+ """
+
+ dnskey = _make_dnskey(public_key, algorithm, flags, protocol)
+
+ return CDNSKEY(
+ rdclass=dnskey.rdclass,
+ rdtype=dns.rdatatype.CDNSKEY,
+ flags=dnskey.flags,
+ protocol=dnskey.protocol,
+ algorithm=dnskey.algorithm,
+ key=dnskey.key,
+ )
+
+
+def nsec3_hash(
+ domain: Union[dns.name.Name, str],
+ salt: Optional[Union[str, bytes]],
+ iterations: int,
+ algorithm: Union[int, str],
+) -> str:
+ """
+ Calculate the NSEC3 hash, according to
+ https://tools.ietf.org/html/rfc5155#section-5
+
+ *domain*, a ``dns.name.Name`` or ``str``, the name to hash.
+
+ *salt*, a ``str``, ``bytes``, or ``None``, the hash salt. If a
+ string, it is decoded as a hex string.
+
+ *iterations*, an ``int``, the number of iterations.
+
+ *algorithm*, a ``str`` or ``int``, the hash algorithm.
+ The only defined algorithm is SHA1.
+
+ Returns a ``str``, the encoded NSEC3 hash.
+ """
+
+ b32_conversion = str.maketrans(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "0123456789ABCDEFGHIJKLMNOPQRSTUV"
+ )
+
+ try:
+ if isinstance(algorithm, str):
+ algorithm = NSEC3Hash[algorithm.upper()]
+ except Exception:
+ raise ValueError("Wrong hash algorithm (only SHA1 is supported)")
+
+ if algorithm != NSEC3Hash.SHA1:
+ raise ValueError("Wrong hash algorithm (only SHA1 is supported)")
+
+ if salt is None:
+ salt_encoded = b""
+ elif isinstance(salt, str):
+ if len(salt) % 2 == 0:
+ salt_encoded = bytes.fromhex(salt)
+ else:
+ raise ValueError("Invalid salt length")
+ else:
+ salt_encoded = salt
+
+ if not isinstance(domain, dns.name.Name):
+ domain = dns.name.from_text(domain)
+ domain_encoded = domain.canonicalize().to_wire()
+ assert domain_encoded is not None
+
+ digest = hashlib.sha1(domain_encoded + salt_encoded).digest()
+ for _ in range(iterations):
+ digest = hashlib.sha1(digest + salt_encoded).digest()
+
+ output = base64.b32encode(digest).decode("utf-8")
+ output = output.translate(b32_conversion)
+
+ return output
+
+
+def make_ds_rdataset(
+ rrset: Union[dns.rrset.RRset, Tuple[dns.name.Name, dns.rdataset.Rdataset]],
+ algorithms: Set[Union[DSDigest, str]],
+ origin: Optional[dns.name.Name] = None,
+) -> dns.rdataset.Rdataset:
+ """Create a DS record from DNSKEY/CDNSKEY/CDS.
+
+ *rrset*, the RRset to create DS Rdataset for. This can be a
+ ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
+ tuple.
+
+ *algorithms*, a set of ``str`` or ``int`` specifying the hash algorithms.
+ The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
+ does not matter for these strings. If the RRset is a CDS, only digest
+ algorithms matching algorithms are accepted.
+
+ *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name,
+ then it will be made absolute using the specified origin.
+
+ Raises ``UnsupportedAlgorithm`` if any of the algorithms are unknown and
+ ``ValueError`` if the given RRset is not usable.
+
+ Returns a ``dns.rdataset.Rdataset``
+ """
+
+ rrname, rdataset = _get_rrname_rdataset(rrset)
+
+ if rdataset.rdtype not in (
+ dns.rdatatype.DNSKEY,
+ dns.rdatatype.CDNSKEY,
+ dns.rdatatype.CDS,
+ ):
+ raise ValueError("rrset not a DNSKEY/CDNSKEY/CDS")
+
+ _algorithms = set()
+ for algorithm in algorithms:
+ try:
+ if isinstance(algorithm, str):
+ algorithm = DSDigest[algorithm.upper()]
+ except Exception:
+ raise UnsupportedAlgorithm('unsupported algorithm "%s"' % algorithm)
+ _algorithms.add(algorithm)
+
+ if rdataset.rdtype == dns.rdatatype.CDS:
+ res = []
+ for rdata in cds_rdataset_to_ds_rdataset(rdataset):
+ if rdata.digest_type in _algorithms:
+ res.append(rdata)
+ if len(res) == 0:
+ raise ValueError("no acceptable CDS rdata found")
+ return dns.rdataset.from_rdata_list(rdataset.ttl, res)
+
+ res = []
+ for algorithm in _algorithms:
+ res.extend(dnskey_rdataset_to_cds_rdataset(rrname, rdataset, algorithm, origin))
+ return dns.rdataset.from_rdata_list(rdataset.ttl, res)
+
+
+def cds_rdataset_to_ds_rdataset(
+ rdataset: dns.rdataset.Rdataset,
+) -> dns.rdataset.Rdataset:
+ """Create a CDS record from DS.
+
+ *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for.
+
+ Raises ``ValueError`` if the rdataset is not CDS.
+
+ Returns a ``dns.rdataset.Rdataset``
+ """
+
+ if rdataset.rdtype != dns.rdatatype.CDS:
+ raise ValueError("rdataset not a CDS")
+ res = []
+ for rdata in rdataset:
+ res.append(
+ CDS(
+ rdclass=rdata.rdclass,
+ rdtype=dns.rdatatype.DS,
+ key_tag=rdata.key_tag,
+ algorithm=rdata.algorithm,
+ digest_type=rdata.digest_type,
+ digest=rdata.digest,
+ )
+ )
+ return dns.rdataset.from_rdata_list(rdataset.ttl, res)
+
+
+def dnskey_rdataset_to_cds_rdataset(
+ name: Union[dns.name.Name, str],
+ rdataset: dns.rdataset.Rdataset,
+ algorithm: Union[DSDigest, str],
+ origin: Optional[dns.name.Name] = None,
+) -> dns.rdataset.Rdataset:
+ """Create a CDS record from DNSKEY/CDNSKEY.
+
+ *name*, a ``dns.name.Name`` or ``str``, the owner name of the CDS record.
+
+ *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for.
+
+ *algorithm*, a ``str`` or ``int`` specifying the hash algorithm.
+ The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
+ does not matter for these strings.
+
+ *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name,
+ then it will be made absolute using the specified origin.
+
+ Raises ``UnsupportedAlgorithm`` if the algorithm is unknown or
+ ``ValueError`` if the rdataset is not DNSKEY/CDNSKEY.
+
+ Returns a ``dns.rdataset.Rdataset``
+ """
+
+ if rdataset.rdtype not in (dns.rdatatype.DNSKEY, dns.rdatatype.CDNSKEY):
+ raise ValueError("rdataset not a DNSKEY/CDNSKEY")
+ res = []
+ for rdata in rdataset:
+ res.append(make_cds(name, rdata, algorithm, origin))
+ return dns.rdataset.from_rdata_list(rdataset.ttl, res)
+
+
+def dnskey_rdataset_to_cdnskey_rdataset(
+ rdataset: dns.rdataset.Rdataset,
+) -> dns.rdataset.Rdataset:
+ """Create a CDNSKEY record from DNSKEY.
+
+ *rdataset*, a ``dns.rdataset.Rdataset``, to create CDNSKEY Rdataset for.
+
+ Returns a ``dns.rdataset.Rdataset``
+ """
+
+ if rdataset.rdtype != dns.rdatatype.DNSKEY:
+ raise ValueError("rdataset not a DNSKEY")
+ res = []
+ for rdata in rdataset:
+ res.append(
+ CDNSKEY(
+ rdclass=rdataset.rdclass,
+ rdtype=rdataset.rdtype,
+ flags=rdata.flags,
+ protocol=rdata.protocol,
+ algorithm=rdata.algorithm,
+ key=rdata.key,
+ )
+ )
+ return dns.rdataset.from_rdata_list(rdataset.ttl, res)
+
+
+def default_rrset_signer(
+ txn: dns.transaction.Transaction,
+ rrset: dns.rrset.RRset,
+ signer: dns.name.Name,
+ ksks: List[Tuple[PrivateKey, DNSKEY]],
+ zsks: List[Tuple[PrivateKey, DNSKEY]],
+ inception: Optional[Union[datetime, str, int, float]] = None,
+ expiration: Optional[Union[datetime, str, int, float]] = None,
+ lifetime: Optional[int] = None,
+ policy: Optional[Policy] = None,
+ origin: Optional[dns.name.Name] = None,
+) -> None:
+ """Default RRset signer"""
+
+ if rrset.rdtype in set(
+ [
+ dns.rdatatype.RdataType.DNSKEY,
+ dns.rdatatype.RdataType.CDS,
+ dns.rdatatype.RdataType.CDNSKEY,
+ ]
+ ):
+ keys = ksks
+ else:
+ keys = zsks
+
+ for private_key, dnskey in keys:
+ rrsig = dns.dnssec.sign(
+ rrset=rrset,
+ private_key=private_key,
+ dnskey=dnskey,
+ inception=inception,
+ expiration=expiration,
+ lifetime=lifetime,
+ signer=signer,
+ policy=policy,
+ origin=origin,
+ )
+ txn.add(rrset.name, rrset.ttl, rrsig)
+
+
+def sign_zone(
+ zone: dns.zone.Zone,
+ txn: Optional[dns.transaction.Transaction] = None,
+ keys: Optional[List[Tuple[PrivateKey, DNSKEY]]] = None,
+ add_dnskey: bool = True,
+ dnskey_ttl: Optional[int] = None,
+ inception: Optional[Union[datetime, str, int, float]] = None,
+ expiration: Optional[Union[datetime, str, int, float]] = None,
+ lifetime: Optional[int] = None,
+ nsec3: Optional[NSEC3PARAM] = None,
+ rrset_signer: Optional[RRsetSigner] = None,
+ policy: Optional[Policy] = None,
+) -> None:
+ """Sign zone.
+
+ *zone*, a ``dns.zone.Zone``, the zone to sign.
+
+ *txn*, a ``dns.transaction.Transaction``, an optional transaction to use for
+ signing.
+
+ *keys*, a list of (``PrivateKey``, ``DNSKEY``) tuples, to use for signing. KSK/ZSK
+ roles are assigned automatically if the SEP flag is used, otherwise all RRsets are
+ signed by all keys.
+
+ *add_dnskey*, a ``bool``. If ``True``, the default, all specified DNSKEYs are
+ automatically added to the zone on signing.
+
+ *dnskey_ttl*, a``int``, specifies the TTL for DNSKEY RRs. If not specified the TTL
+ of the existing DNSKEY RRset used or the TTL of the SOA RRset.
+
+ *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature
+ inception time. If ``None``, the current time is used. If a ``str``, the format is
+ "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX epoch in text
+ form; this is the same the RRSIG rdata's text form. Values of type `int` or `float`
+ are interpreted as seconds since the UNIX epoch.
+
+ *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature
+ expiration time. If ``None``, the expiration time will be the inception time plus
+ the value of the *lifetime* parameter. See the description of *inception* above for
+ how the various parameter types are interpreted.
+
+ *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This
+ parameter is only meaningful if *expiration* is ``None``.
+
+ *nsec3*, a ``NSEC3PARAM`` Rdata, configures signing using NSEC3. Not yet
+ implemented.
+
+ *rrset_signer*, a ``Callable``, an optional function for signing RRsets. The
+ function requires two arguments: transaction and RRset. If the not specified,
+ ``dns.dnssec.default_rrset_signer`` will be used.
+
+ Returns ``None``.
+ """
+
+ ksks = []
+ zsks = []
+
+ # if we have both KSKs and ZSKs, split by SEP flag. if not, sign all
+ # records with all keys
+ if keys:
+ for key in keys:
+ if key[1].flags & Flag.SEP:
+ ksks.append(key)
+ else:
+ zsks.append(key)
+ if not ksks:
+ ksks = keys
+ if not zsks:
+ zsks = keys
+ else:
+ keys = []
+
+ if txn:
+ cm: contextlib.AbstractContextManager = contextlib.nullcontext(txn)
+ else:
+ cm = zone.writer()
+
+ with cm as _txn:
+ if add_dnskey:
+ if dnskey_ttl is None:
+ dnskey = _txn.get(zone.origin, dns.rdatatype.DNSKEY)
+ if dnskey:
+ dnskey_ttl = dnskey.ttl
+ else:
+ soa = _txn.get(zone.origin, dns.rdatatype.SOA)
+ dnskey_ttl = soa.ttl
+ for _, dnskey in keys:
+ _txn.add(zone.origin, dnskey_ttl, dnskey)
+
+ if nsec3:
+ raise NotImplementedError("Signing with NSEC3 not yet implemented")
+ else:
+ _rrset_signer = rrset_signer or functools.partial(
+ default_rrset_signer,
+ signer=zone.origin,
+ ksks=ksks,
+ zsks=zsks,
+ inception=inception,
+ expiration=expiration,
+ lifetime=lifetime,
+ policy=policy,
+ origin=zone.origin,
+ )
+ return _sign_zone_nsec(zone, _txn, _rrset_signer)
+
+
+def _sign_zone_nsec(
+ zone: dns.zone.Zone,
+ txn: dns.transaction.Transaction,
+ rrset_signer: Optional[RRsetSigner] = None,
+) -> None:
+ """NSEC zone signer"""
+
+ def _txn_add_nsec(
+ txn: dns.transaction.Transaction,
+ name: dns.name.Name,
+ next_secure: Optional[dns.name.Name],
+ rdclass: dns.rdataclass.RdataClass,
+ ttl: int,
+ rrset_signer: Optional[RRsetSigner] = None,
+ ) -> None:
+ """NSEC zone signer helper"""
+ mandatory_types = set(
+ [dns.rdatatype.RdataType.RRSIG, dns.rdatatype.RdataType.NSEC]
+ )
+ node = txn.get_node(name)
+ if node and next_secure:
+ types = (
+ set([rdataset.rdtype for rdataset in node.rdatasets]) | mandatory_types
+ )
+ windows = Bitmap.from_rdtypes(list(types))
+ rrset = dns.rrset.from_rdata(
+ name,
+ ttl,
+ NSEC(
+ rdclass=rdclass,
+ rdtype=dns.rdatatype.RdataType.NSEC,
+ next=next_secure,
+ windows=windows,
+ ),
+ )
+ txn.add(rrset)
+ if rrset_signer:
+ rrset_signer(txn, rrset)
+
+ rrsig_ttl = zone.get_soa().minimum
+ delegation = None
+ last_secure = None
+
+ for name in sorted(txn.iterate_names()):
+ if delegation and name.is_subdomain(delegation):
+ # names below delegations are not secure
+ continue
+ elif txn.get(name, dns.rdatatype.NS) and name != zone.origin:
+ # inside delegation
+ delegation = name
+ else:
+ # outside delegation
+ delegation = None
+
+ if rrset_signer:
+ node = txn.get_node(name)
+ if node:
+ for rdataset in node.rdatasets:
+ if rdataset.rdtype == dns.rdatatype.RRSIG:
+ # do not sign RRSIGs
+ continue
+ elif delegation and rdataset.rdtype != dns.rdatatype.DS:
+ # do not sign delegations except DS records
+ continue
+ else:
+ rrset = dns.rrset.from_rdata(name, rdataset.ttl, *rdataset)
+ rrset_signer(txn, rrset)
+
+ # We need "is not None" as the empty name is False because its length is 0.
+ if last_secure is not None:
+ _txn_add_nsec(txn, last_secure, name, zone.rdclass, rrsig_ttl, rrset_signer)
+ last_secure = name
+
+ if last_secure:
+ _txn_add_nsec(
+ txn, last_secure, zone.origin, zone.rdclass, rrsig_ttl, rrset_signer
+ )
+
+
+def _need_pyca(*args, **kwargs):
+ raise ImportError(
+ "DNSSEC validation requires python cryptography"
+ ) # pragma: no cover
+
+
+if dns._features.have("dnssec"):
+ from cryptography.exceptions import InvalidSignature
+ from cryptography.hazmat.primitives.asymmetric import dsa # pylint: disable=W0611
+ from cryptography.hazmat.primitives.asymmetric import ec # pylint: disable=W0611
+ from cryptography.hazmat.primitives.asymmetric import ed448 # pylint: disable=W0611
+ from cryptography.hazmat.primitives.asymmetric import rsa # pylint: disable=W0611
+ from cryptography.hazmat.primitives.asymmetric import ( # pylint: disable=W0611
+ ed25519,
+ )
+
+ from dns.dnssecalgs import ( # pylint: disable=C0412
+ get_algorithm_cls,
+ get_algorithm_cls_from_dnskey,
+ )
+ from dns.dnssecalgs.base import GenericPrivateKey, GenericPublicKey
+
+ validate = _validate # type: ignore
+ validate_rrsig = _validate_rrsig # type: ignore
+ sign = _sign
+ make_dnskey = _make_dnskey
+ make_cdnskey = _make_cdnskey
+ _have_pyca = True
+else: # pragma: no cover
+ validate = _need_pyca
+ validate_rrsig = _need_pyca
+ sign = _need_pyca
+ make_dnskey = _need_pyca
+ make_cdnskey = _need_pyca
+ _have_pyca = False
+
+### BEGIN generated Algorithm constants
+
+RSAMD5 = Algorithm.RSAMD5
+DH = Algorithm.DH
+DSA = Algorithm.DSA
+ECC = Algorithm.ECC
+RSASHA1 = Algorithm.RSASHA1
+DSANSEC3SHA1 = Algorithm.DSANSEC3SHA1
+RSASHA1NSEC3SHA1 = Algorithm.RSASHA1NSEC3SHA1
+RSASHA256 = Algorithm.RSASHA256
+RSASHA512 = Algorithm.RSASHA512
+ECCGOST = Algorithm.ECCGOST
+ECDSAP256SHA256 = Algorithm.ECDSAP256SHA256
+ECDSAP384SHA384 = Algorithm.ECDSAP384SHA384
+ED25519 = Algorithm.ED25519
+ED448 = Algorithm.ED448
+INDIRECT = Algorithm.INDIRECT
+PRIVATEDNS = Algorithm.PRIVATEDNS
+PRIVATEOID = Algorithm.PRIVATEOID
+
+### END generated Algorithm constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/dnssectypes.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/dnssectypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..02131e0adaeb85eb49351f4953c854023315fab9
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/dnssectypes.py
@@ -0,0 +1,71 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Common DNSSEC-related types."""
+
+# This is a separate file to avoid import circularity between dns.dnssec and
+# the implementations of the DS and DNSKEY types.
+
+import dns.enum
+
+
+class Algorithm(dns.enum.IntEnum):
+ RSAMD5 = 1
+ DH = 2
+ DSA = 3
+ ECC = 4
+ RSASHA1 = 5
+ DSANSEC3SHA1 = 6
+ RSASHA1NSEC3SHA1 = 7
+ RSASHA256 = 8
+ RSASHA512 = 10
+ ECCGOST = 12
+ ECDSAP256SHA256 = 13
+ ECDSAP384SHA384 = 14
+ ED25519 = 15
+ ED448 = 16
+ INDIRECT = 252
+ PRIVATEDNS = 253
+ PRIVATEOID = 254
+
+ @classmethod
+ def _maximum(cls):
+ return 255
+
+
+class DSDigest(dns.enum.IntEnum):
+ """DNSSEC Delegation Signer Digest Algorithm"""
+
+ NULL = 0
+ SHA1 = 1
+ SHA256 = 2
+ GOST = 3
+ SHA384 = 4
+
+ @classmethod
+ def _maximum(cls):
+ return 255
+
+
+class NSEC3Hash(dns.enum.IntEnum):
+ """NSEC3 hash algorithm"""
+
+ SHA1 = 1
+
+ @classmethod
+ def _maximum(cls):
+ return 255
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/e164.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/e164.py
new file mode 100644
index 0000000000000000000000000000000000000000..453736d40806838131569785f5eb2c65b8a2c310
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/e164.py
@@ -0,0 +1,116 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2006-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS E.164 helpers."""
+
+from typing import Iterable, Optional, Union
+
+import dns.exception
+import dns.name
+import dns.resolver
+
+#: The public E.164 domain.
+public_enum_domain = dns.name.from_text("e164.arpa.")
+
+
+def from_e164(
+ text: str, origin: Optional[dns.name.Name] = public_enum_domain
+) -> dns.name.Name:
+ """Convert an E.164 number in textual form into a Name object whose
+ value is the ENUM domain name for that number.
+
+ Non-digits in the text are ignored, i.e. "16505551212",
+ "+1.650.555.1212" and "1 (650) 555-1212" are all the same.
+
+ *text*, a ``str``, is an E.164 number in textual form.
+
+ *origin*, a ``dns.name.Name``, the domain in which the number
+ should be constructed. The default is ``e164.arpa.``.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ parts = [d for d in text if d.isdigit()]
+ parts.reverse()
+ return dns.name.from_text(".".join(parts), origin=origin)
+
+
+def to_e164(
+ name: dns.name.Name,
+ origin: Optional[dns.name.Name] = public_enum_domain,
+ want_plus_prefix: bool = True,
+) -> str:
+ """Convert an ENUM domain name into an E.164 number.
+
+ Note that dnspython does not have any information about preferred
+ number formats within national numbering plans, so all numbers are
+ emitted as a simple string of digits, prefixed by a '+' (unless
+ *want_plus_prefix* is ``False``).
+
+ *name* is a ``dns.name.Name``, the ENUM domain name.
+
+ *origin* is a ``dns.name.Name``, a domain containing the ENUM
+ domain name. The name is relativized to this domain before being
+ converted to text. If ``None``, no relativization is done.
+
+ *want_plus_prefix* is a ``bool``. If True, add a '+' to the beginning of
+ the returned number.
+
+ Returns a ``str``.
+
+ """
+ if origin is not None:
+ name = name.relativize(origin)
+ dlabels = [d for d in name.labels if d.isdigit() and len(d) == 1]
+ if len(dlabels) != len(name.labels):
+ raise dns.exception.SyntaxError("non-digit labels in ENUM domain name")
+ dlabels.reverse()
+ text = b"".join(dlabels)
+ if want_plus_prefix:
+ text = b"+" + text
+ return text.decode()
+
+
+def query(
+ number: str,
+ domains: Iterable[Union[dns.name.Name, str]],
+ resolver: Optional[dns.resolver.Resolver] = None,
+) -> dns.resolver.Answer:
+ """Look for NAPTR RRs for the specified number in the specified domains.
+
+ e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.'])
+
+ *number*, a ``str`` is the number to look for.
+
+ *domains* is an iterable containing ``dns.name.Name`` values.
+
+ *resolver*, a ``dns.resolver.Resolver``, is the resolver to use. If
+ ``None``, the default resolver is used.
+ """
+
+ if resolver is None:
+ resolver = dns.resolver.get_default_resolver()
+ e_nx = dns.resolver.NXDOMAIN()
+ for domain in domains:
+ if isinstance(domain, str):
+ domain = dns.name.from_text(domain)
+ qname = dns.e164.from_e164(number, domain)
+ try:
+ return resolver.resolve(qname, "NAPTR")
+ except dns.resolver.NXDOMAIN as e:
+ e_nx += e
+ raise e_nx
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/edns.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/edns.py
new file mode 100644
index 0000000000000000000000000000000000000000..776e5eeba7b725ea68e2a1f3ffc7099b7797b709
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/edns.py
@@ -0,0 +1,516 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2009-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""EDNS Options"""
+
+import binascii
+import math
+import socket
+import struct
+from typing import Any, Dict, Optional, Union
+
+import dns.enum
+import dns.inet
+import dns.rdata
+import dns.wire
+
+
+class OptionType(dns.enum.IntEnum):
+ #: NSID
+ NSID = 3
+ #: DAU
+ DAU = 5
+ #: DHU
+ DHU = 6
+ #: N3U
+ N3U = 7
+ #: ECS (client-subnet)
+ ECS = 8
+ #: EXPIRE
+ EXPIRE = 9
+ #: COOKIE
+ COOKIE = 10
+ #: KEEPALIVE
+ KEEPALIVE = 11
+ #: PADDING
+ PADDING = 12
+ #: CHAIN
+ CHAIN = 13
+ #: EDE (extended-dns-error)
+ EDE = 15
+
+ @classmethod
+ def _maximum(cls):
+ return 65535
+
+
+class Option:
+ """Base class for all EDNS option types."""
+
+ def __init__(self, otype: Union[OptionType, str]):
+ """Initialize an option.
+
+ *otype*, a ``dns.edns.OptionType``, is the option type.
+ """
+ self.otype = OptionType.make(otype)
+
+ def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]:
+ """Convert an option to wire format.
+
+ Returns a ``bytes`` or ``None``.
+
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def to_text(self) -> str:
+ raise NotImplementedError # pragma: no cover
+
+ @classmethod
+ def from_wire_parser(cls, otype: OptionType, parser: "dns.wire.Parser") -> "Option":
+ """Build an EDNS option object from wire format.
+
+ *otype*, a ``dns.edns.OptionType``, is the option type.
+
+ *parser*, a ``dns.wire.Parser``, the parser, which should be
+ restructed to the option length.
+
+ Returns a ``dns.edns.Option``.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def _cmp(self, other):
+ """Compare an EDNS option with another option of the same type.
+
+ Returns < 0 if < *other*, 0 if == *other*, and > 0 if > *other*.
+ """
+ wire = self.to_wire()
+ owire = other.to_wire()
+ if wire == owire:
+ return 0
+ if wire > owire:
+ return 1
+ return -1
+
+ def __eq__(self, other):
+ if not isinstance(other, Option):
+ return False
+ if self.otype != other.otype:
+ return False
+ return self._cmp(other) == 0
+
+ def __ne__(self, other):
+ if not isinstance(other, Option):
+ return True
+ if self.otype != other.otype:
+ return True
+ return self._cmp(other) != 0
+
+ def __lt__(self, other):
+ if not isinstance(other, Option) or self.otype != other.otype:
+ return NotImplemented
+ return self._cmp(other) < 0
+
+ def __le__(self, other):
+ if not isinstance(other, Option) or self.otype != other.otype:
+ return NotImplemented
+ return self._cmp(other) <= 0
+
+ def __ge__(self, other):
+ if not isinstance(other, Option) or self.otype != other.otype:
+ return NotImplemented
+ return self._cmp(other) >= 0
+
+ def __gt__(self, other):
+ if not isinstance(other, Option) or self.otype != other.otype:
+ return NotImplemented
+ return self._cmp(other) > 0
+
+ def __str__(self):
+ return self.to_text()
+
+
+class GenericOption(Option): # lgtm[py/missing-equals]
+ """Generic Option Class
+
+ This class is used for EDNS option types for which we have no better
+ implementation.
+ """
+
+ def __init__(self, otype: Union[OptionType, str], data: Union[bytes, str]):
+ super().__init__(otype)
+ self.data = dns.rdata.Rdata._as_bytes(data, True)
+
+ def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]:
+ if file:
+ file.write(self.data)
+ return None
+ else:
+ return self.data
+
+ def to_text(self) -> str:
+ return "Generic %d" % self.otype
+
+ @classmethod
+ def from_wire_parser(
+ cls, otype: Union[OptionType, str], parser: "dns.wire.Parser"
+ ) -> Option:
+ return cls(otype, parser.get_remaining())
+
+
+class ECSOption(Option): # lgtm[py/missing-equals]
+ """EDNS Client Subnet (ECS, RFC7871)"""
+
+ def __init__(self, address: str, srclen: Optional[int] = None, scopelen: int = 0):
+ """*address*, a ``str``, is the client address information.
+
+ *srclen*, an ``int``, the source prefix length, which is the
+ leftmost number of bits of the address to be used for the
+ lookup. The default is 24 for IPv4 and 56 for IPv6.
+
+ *scopelen*, an ``int``, the scope prefix length. This value
+ must be 0 in queries, and should be set in responses.
+ """
+
+ super().__init__(OptionType.ECS)
+ af = dns.inet.af_for_address(address)
+
+ if af == socket.AF_INET6:
+ self.family = 2
+ if srclen is None:
+ srclen = 56
+ address = dns.rdata.Rdata._as_ipv6_address(address)
+ srclen = dns.rdata.Rdata._as_int(srclen, 0, 128)
+ scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 128)
+ elif af == socket.AF_INET:
+ self.family = 1
+ if srclen is None:
+ srclen = 24
+ address = dns.rdata.Rdata._as_ipv4_address(address)
+ srclen = dns.rdata.Rdata._as_int(srclen, 0, 32)
+ scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 32)
+ else: # pragma: no cover (this will never happen)
+ raise ValueError("Bad address family")
+
+ assert srclen is not None
+ self.address = address
+ self.srclen = srclen
+ self.scopelen = scopelen
+
+ addrdata = dns.inet.inet_pton(af, address)
+ nbytes = int(math.ceil(srclen / 8.0))
+
+ # Truncate to srclen and pad to the end of the last octet needed
+ # See RFC section 6
+ self.addrdata = addrdata[:nbytes]
+ nbits = srclen % 8
+ if nbits != 0:
+ last = struct.pack("B", ord(self.addrdata[-1:]) & (0xFF << (8 - nbits)))
+ self.addrdata = self.addrdata[:-1] + last
+
+ def to_text(self) -> str:
+ return "ECS {}/{} scope/{}".format(self.address, self.srclen, self.scopelen)
+
+ @staticmethod
+ def from_text(text: str) -> Option:
+ """Convert a string into a `dns.edns.ECSOption`
+
+ *text*, a `str`, the text form of the option.
+
+ Returns a `dns.edns.ECSOption`.
+
+ Examples:
+
+ >>> import dns.edns
+ >>>
+ >>> # basic example
+ >>> dns.edns.ECSOption.from_text('1.2.3.4/24')
+ >>>
+ >>> # also understands scope
+ >>> dns.edns.ECSOption.from_text('1.2.3.4/24/32')
+ >>>
+ >>> # IPv6
+ >>> dns.edns.ECSOption.from_text('2001:4b98::1/64/64')
+ >>>
+ >>> # it understands results from `dns.edns.ECSOption.to_text()`
+ >>> dns.edns.ECSOption.from_text('ECS 1.2.3.4/24/32')
+ """
+ optional_prefix = "ECS"
+ tokens = text.split()
+ ecs_text = None
+ if len(tokens) == 1:
+ ecs_text = tokens[0]
+ elif len(tokens) == 2:
+ if tokens[0] != optional_prefix:
+ raise ValueError('could not parse ECS from "{}"'.format(text))
+ ecs_text = tokens[1]
+ else:
+ raise ValueError('could not parse ECS from "{}"'.format(text))
+ n_slashes = ecs_text.count("/")
+ if n_slashes == 1:
+ address, tsrclen = ecs_text.split("/")
+ tscope = "0"
+ elif n_slashes == 2:
+ address, tsrclen, tscope = ecs_text.split("/")
+ else:
+ raise ValueError('could not parse ECS from "{}"'.format(text))
+ try:
+ scope = int(tscope)
+ except ValueError:
+ raise ValueError(
+ "invalid scope " + '"{}": scope must be an integer'.format(tscope)
+ )
+ try:
+ srclen = int(tsrclen)
+ except ValueError:
+ raise ValueError(
+ "invalid srclen " + '"{}": srclen must be an integer'.format(tsrclen)
+ )
+ return ECSOption(address, srclen, scope)
+
+ def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]:
+ value = (
+ struct.pack("!HBB", self.family, self.srclen, self.scopelen) + self.addrdata
+ )
+ if file:
+ file.write(value)
+ return None
+ else:
+ return value
+
+ @classmethod
+ def from_wire_parser(
+ cls, otype: Union[OptionType, str], parser: "dns.wire.Parser"
+ ) -> Option:
+ family, src, scope = parser.get_struct("!HBB")
+ addrlen = int(math.ceil(src / 8.0))
+ prefix = parser.get_bytes(addrlen)
+ if family == 1:
+ pad = 4 - addrlen
+ addr = dns.ipv4.inet_ntoa(prefix + b"\x00" * pad)
+ elif family == 2:
+ pad = 16 - addrlen
+ addr = dns.ipv6.inet_ntoa(prefix + b"\x00" * pad)
+ else:
+ raise ValueError("unsupported family")
+
+ return cls(addr, src, scope)
+
+
+class EDECode(dns.enum.IntEnum):
+ OTHER = 0
+ UNSUPPORTED_DNSKEY_ALGORITHM = 1
+ UNSUPPORTED_DS_DIGEST_TYPE = 2
+ STALE_ANSWER = 3
+ FORGED_ANSWER = 4
+ DNSSEC_INDETERMINATE = 5
+ DNSSEC_BOGUS = 6
+ SIGNATURE_EXPIRED = 7
+ SIGNATURE_NOT_YET_VALID = 8
+ DNSKEY_MISSING = 9
+ RRSIGS_MISSING = 10
+ NO_ZONE_KEY_BIT_SET = 11
+ NSEC_MISSING = 12
+ CACHED_ERROR = 13
+ NOT_READY = 14
+ BLOCKED = 15
+ CENSORED = 16
+ FILTERED = 17
+ PROHIBITED = 18
+ STALE_NXDOMAIN_ANSWER = 19
+ NOT_AUTHORITATIVE = 20
+ NOT_SUPPORTED = 21
+ NO_REACHABLE_AUTHORITY = 22
+ NETWORK_ERROR = 23
+ INVALID_DATA = 24
+
+ @classmethod
+ def _maximum(cls):
+ return 65535
+
+
+class EDEOption(Option): # lgtm[py/missing-equals]
+ """Extended DNS Error (EDE, RFC8914)"""
+
+ _preserve_case = {"DNSKEY", "DS", "DNSSEC", "RRSIGs", "NSEC", "NXDOMAIN"}
+
+ def __init__(self, code: Union[EDECode, str], text: Optional[str] = None):
+ """*code*, a ``dns.edns.EDECode`` or ``str``, the info code of the
+ extended error.
+
+ *text*, a ``str`` or ``None``, specifying additional information about
+ the error.
+ """
+
+ super().__init__(OptionType.EDE)
+
+ self.code = EDECode.make(code)
+ if text is not None and not isinstance(text, str):
+ raise ValueError("text must be string or None")
+ self.text = text
+
+ def to_text(self) -> str:
+ output = f"EDE {self.code}"
+ if self.code in EDECode:
+ desc = EDECode.to_text(self.code)
+ desc = " ".join(
+ word if word in self._preserve_case else word.title()
+ for word in desc.split("_")
+ )
+ output += f" ({desc})"
+ if self.text is not None:
+ output += f": {self.text}"
+ return output
+
+ def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]:
+ value = struct.pack("!H", self.code)
+ if self.text is not None:
+ value += self.text.encode("utf8")
+
+ if file:
+ file.write(value)
+ return None
+ else:
+ return value
+
+ @classmethod
+ def from_wire_parser(
+ cls, otype: Union[OptionType, str], parser: "dns.wire.Parser"
+ ) -> Option:
+ code = EDECode.make(parser.get_uint16())
+ text = parser.get_remaining()
+
+ if text:
+ if text[-1] == 0: # text MAY be null-terminated
+ text = text[:-1]
+ btext = text.decode("utf8")
+ else:
+ btext = None
+
+ return cls(code, btext)
+
+
+class NSIDOption(Option):
+ def __init__(self, nsid: bytes):
+ super().__init__(OptionType.NSID)
+ self.nsid = nsid
+
+ def to_wire(self, file: Any = None) -> Optional[bytes]:
+ if file:
+ file.write(self.nsid)
+ return None
+ else:
+ return self.nsid
+
+ def to_text(self) -> str:
+ if all(c >= 0x20 and c <= 0x7E for c in self.nsid):
+ # All ASCII printable, so it's probably a string.
+ value = self.nsid.decode()
+ else:
+ value = binascii.hexlify(self.nsid).decode()
+ return f"NSID {value}"
+
+ @classmethod
+ def from_wire_parser(
+ cls, otype: Union[OptionType, str], parser: dns.wire.Parser
+ ) -> Option:
+ return cls(parser.get_remaining())
+
+
+_type_to_class: Dict[OptionType, Any] = {
+ OptionType.ECS: ECSOption,
+ OptionType.EDE: EDEOption,
+ OptionType.NSID: NSIDOption,
+}
+
+
+def get_option_class(otype: OptionType) -> Any:
+ """Return the class for the specified option type.
+
+ The GenericOption class is used if a more specific class is not
+ known.
+ """
+
+ cls = _type_to_class.get(otype)
+ if cls is None:
+ cls = GenericOption
+ return cls
+
+
+def option_from_wire_parser(
+ otype: Union[OptionType, str], parser: "dns.wire.Parser"
+) -> Option:
+ """Build an EDNS option object from wire format.
+
+ *otype*, an ``int``, is the option type.
+
+ *parser*, a ``dns.wire.Parser``, the parser, which should be
+ restricted to the option length.
+
+ Returns an instance of a subclass of ``dns.edns.Option``.
+ """
+ otype = OptionType.make(otype)
+ cls = get_option_class(otype)
+ return cls.from_wire_parser(otype, parser)
+
+
+def option_from_wire(
+ otype: Union[OptionType, str], wire: bytes, current: int, olen: int
+) -> Option:
+ """Build an EDNS option object from wire format.
+
+ *otype*, an ``int``, is the option type.
+
+ *wire*, a ``bytes``, is the wire-format message.
+
+ *current*, an ``int``, is the offset in *wire* of the beginning
+ of the rdata.
+
+ *olen*, an ``int``, is the length of the wire-format option data
+
+ Returns an instance of a subclass of ``dns.edns.Option``.
+ """
+ parser = dns.wire.Parser(wire, current)
+ with parser.restrict_to(olen):
+ return option_from_wire_parser(otype, parser)
+
+
+def register_type(implementation: Any, otype: OptionType) -> None:
+ """Register the implementation of an option type.
+
+ *implementation*, a ``class``, is a subclass of ``dns.edns.Option``.
+
+ *otype*, an ``int``, is the option type.
+ """
+
+ _type_to_class[otype] = implementation
+
+
+### BEGIN generated OptionType constants
+
+NSID = OptionType.NSID
+DAU = OptionType.DAU
+DHU = OptionType.DHU
+N3U = OptionType.N3U
+ECS = OptionType.ECS
+EXPIRE = OptionType.EXPIRE
+COOKIE = OptionType.COOKIE
+KEEPALIVE = OptionType.KEEPALIVE
+PADDING = OptionType.PADDING
+CHAIN = OptionType.CHAIN
+EDE = OptionType.EDE
+
+### END generated OptionType constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/entropy.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/entropy.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dcdc6272ca3a670b1616f4c95f2a18b1803bc82
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/entropy.py
@@ -0,0 +1,130 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2009-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+import hashlib
+import os
+import random
+import threading
+import time
+from typing import Any, Optional
+
+
+class EntropyPool:
+ # This is an entropy pool for Python implementations that do not
+ # have a working SystemRandom. I'm not sure there are any, but
+ # leaving this code doesn't hurt anything as the library code
+ # is used if present.
+
+ def __init__(self, seed: Optional[bytes] = None):
+ self.pool_index = 0
+ self.digest: Optional[bytearray] = None
+ self.next_byte = 0
+ self.lock = threading.Lock()
+ self.hash = hashlib.sha1()
+ self.hash_len = 20
+ self.pool = bytearray(b"\0" * self.hash_len)
+ if seed is not None:
+ self._stir(seed)
+ self.seeded = True
+ self.seed_pid = os.getpid()
+ else:
+ self.seeded = False
+ self.seed_pid = 0
+
+ def _stir(self, entropy: bytes) -> None:
+ for c in entropy:
+ if self.pool_index == self.hash_len:
+ self.pool_index = 0
+ b = c & 0xFF
+ self.pool[self.pool_index] ^= b
+ self.pool_index += 1
+
+ def stir(self, entropy: bytes) -> None:
+ with self.lock:
+ self._stir(entropy)
+
+ def _maybe_seed(self) -> None:
+ if not self.seeded or self.seed_pid != os.getpid():
+ try:
+ seed = os.urandom(16)
+ except Exception: # pragma: no cover
+ try:
+ with open("/dev/urandom", "rb", 0) as r:
+ seed = r.read(16)
+ except Exception:
+ seed = str(time.time()).encode()
+ self.seeded = True
+ self.seed_pid = os.getpid()
+ self.digest = None
+ seed = bytearray(seed)
+ self._stir(seed)
+
+ def random_8(self) -> int:
+ with self.lock:
+ self._maybe_seed()
+ if self.digest is None or self.next_byte == self.hash_len:
+ self.hash.update(bytes(self.pool))
+ self.digest = bytearray(self.hash.digest())
+ self._stir(self.digest)
+ self.next_byte = 0
+ value = self.digest[self.next_byte]
+ self.next_byte += 1
+ return value
+
+ def random_16(self) -> int:
+ return self.random_8() * 256 + self.random_8()
+
+ def random_32(self) -> int:
+ return self.random_16() * 65536 + self.random_16()
+
+ def random_between(self, first: int, last: int) -> int:
+ size = last - first + 1
+ if size > 4294967296:
+ raise ValueError("too big")
+ if size > 65536:
+ rand = self.random_32
+ max = 4294967295
+ elif size > 256:
+ rand = self.random_16
+ max = 65535
+ else:
+ rand = self.random_8
+ max = 255
+ return first + size * rand() // (max + 1)
+
+
+pool = EntropyPool()
+
+system_random: Optional[Any]
+try:
+ system_random = random.SystemRandom()
+except Exception: # pragma: no cover
+ system_random = None
+
+
+def random_16() -> int:
+ if system_random is not None:
+ return system_random.randrange(0, 65536)
+ else:
+ return pool.random_16()
+
+
+def between(first: int, last: int) -> int:
+ if system_random is not None:
+ return system_random.randrange(first, last + 1)
+ else:
+ return pool.random_between(first, last)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/enum.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/enum.py
new file mode 100644
index 0000000000000000000000000000000000000000..71461f1776f3990311f656cb37f6aab68e0b9f71
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/enum.py
@@ -0,0 +1,116 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+import enum
+from typing import Type, TypeVar, Union
+
+TIntEnum = TypeVar("TIntEnum", bound="IntEnum")
+
+
+class IntEnum(enum.IntEnum):
+ @classmethod
+ def _missing_(cls, value):
+ cls._check_value(value)
+ val = int.__new__(cls, value)
+ val._name_ = cls._extra_to_text(value, None) or f"{cls._prefix()}{value}"
+ val._value_ = value
+ return val
+
+ @classmethod
+ def _check_value(cls, value):
+ max = cls._maximum()
+ if not isinstance(value, int):
+ raise TypeError
+ if value < 0 or value > max:
+ name = cls._short_name()
+ raise ValueError(f"{name} must be an int between >= 0 and <= {max}")
+
+ @classmethod
+ def from_text(cls: Type[TIntEnum], text: str) -> TIntEnum:
+ text = text.upper()
+ try:
+ return cls[text]
+ except KeyError:
+ pass
+ value = cls._extra_from_text(text)
+ if value:
+ return value
+ prefix = cls._prefix()
+ if text.startswith(prefix) and text[len(prefix) :].isdigit():
+ value = int(text[len(prefix) :])
+ cls._check_value(value)
+ try:
+ return cls(value)
+ except ValueError:
+ return value
+ raise cls._unknown_exception_class()
+
+ @classmethod
+ def to_text(cls: Type[TIntEnum], value: int) -> str:
+ cls._check_value(value)
+ try:
+ text = cls(value).name
+ except ValueError:
+ text = None
+ text = cls._extra_to_text(value, text)
+ if text is None:
+ text = f"{cls._prefix()}{value}"
+ return text
+
+ @classmethod
+ def make(cls: Type[TIntEnum], value: Union[int, str]) -> TIntEnum:
+ """Convert text or a value into an enumerated type, if possible.
+
+ *value*, the ``int`` or ``str`` to convert.
+
+ Raises a class-specific exception if a ``str`` is provided that
+ cannot be converted.
+
+ Raises ``ValueError`` if the value is out of range.
+
+ Returns an enumeration from the calling class corresponding to the
+ value, if one is defined, or an ``int`` otherwise.
+ """
+
+ if isinstance(value, str):
+ return cls.from_text(value)
+ cls._check_value(value)
+ return cls(value)
+
+ @classmethod
+ def _maximum(cls):
+ raise NotImplementedError # pragma: no cover
+
+ @classmethod
+ def _short_name(cls):
+ return cls.__name__.lower()
+
+ @classmethod
+ def _prefix(cls):
+ return ""
+
+ @classmethod
+ def _extra_from_text(cls, text): # pylint: disable=W0613
+ return None
+
+ @classmethod
+ def _extra_to_text(cls, value, current_text): # pylint: disable=W0613
+ return current_text
+
+ @classmethod
+ def _unknown_exception_class(cls):
+ return ValueError
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/exception.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/exception.py
new file mode 100644
index 0000000000000000000000000000000000000000..6982373de2a872057ca1fda3a2a752ff8d566355
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/exception.py
@@ -0,0 +1,169 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Common DNS Exceptions.
+
+Dnspython modules may also define their own exceptions, which will
+always be subclasses of ``DNSException``.
+"""
+
+
+from typing import Optional, Set
+
+
+class DNSException(Exception):
+ """Abstract base class shared by all dnspython exceptions.
+
+ It supports two basic modes of operation:
+
+ a) Old/compatible mode is used if ``__init__`` was called with
+ empty *kwargs*. In compatible mode all *args* are passed
+ to the standard Python Exception class as before and all *args* are
+ printed by the standard ``__str__`` implementation. Class variable
+ ``msg`` (or doc string if ``msg`` is ``None``) is returned from ``str()``
+ if *args* is empty.
+
+ b) New/parametrized mode is used if ``__init__`` was called with
+ non-empty *kwargs*.
+ In the new mode *args* must be empty and all kwargs must match
+ those set in class variable ``supp_kwargs``. All kwargs are stored inside
+ ``self.kwargs`` and used in a new ``__str__`` implementation to construct
+ a formatted message based on the ``fmt`` class variable, a ``string``.
+
+ In the simplest case it is enough to override the ``supp_kwargs``
+ and ``fmt`` class variables to get nice parametrized messages.
+ """
+
+ msg: Optional[str] = None # non-parametrized message
+ supp_kwargs: Set[str] = set() # accepted parameters for _fmt_kwargs (sanity check)
+ fmt: Optional[str] = None # message parametrized with results from _fmt_kwargs
+
+ def __init__(self, *args, **kwargs):
+ self._check_params(*args, **kwargs)
+ if kwargs:
+ # This call to a virtual method from __init__ is ok in our usage
+ self.kwargs = self._check_kwargs(**kwargs) # lgtm[py/init-calls-subclass]
+ self.msg = str(self)
+ else:
+ self.kwargs = dict() # defined but empty for old mode exceptions
+ if self.msg is None:
+ # doc string is better implicit message than empty string
+ self.msg = self.__doc__
+ if args:
+ super().__init__(*args)
+ else:
+ super().__init__(self.msg)
+
+ def _check_params(self, *args, **kwargs):
+ """Old exceptions supported only args and not kwargs.
+
+ For sanity we do not allow to mix old and new behavior."""
+ if args or kwargs:
+ assert bool(args) != bool(
+ kwargs
+ ), "keyword arguments are mutually exclusive with positional args"
+
+ def _check_kwargs(self, **kwargs):
+ if kwargs:
+ assert (
+ set(kwargs.keys()) == self.supp_kwargs
+ ), "following set of keyword args is required: %s" % (self.supp_kwargs)
+ return kwargs
+
+ def _fmt_kwargs(self, **kwargs):
+ """Format kwargs before printing them.
+
+ Resulting dictionary has to have keys necessary for str.format call
+ on fmt class variable.
+ """
+ fmtargs = {}
+ for kw, data in kwargs.items():
+ if isinstance(data, (list, set)):
+ # convert list of to list of str()
+ fmtargs[kw] = list(map(str, data))
+ if len(fmtargs[kw]) == 1:
+ # remove list brackets [] from single-item lists
+ fmtargs[kw] = fmtargs[kw].pop()
+ else:
+ fmtargs[kw] = data
+ return fmtargs
+
+ def __str__(self):
+ if self.kwargs and self.fmt:
+ # provide custom message constructed from keyword arguments
+ fmtargs = self._fmt_kwargs(**self.kwargs)
+ return self.fmt.format(**fmtargs)
+ else:
+ # print *args directly in the same way as old DNSException
+ return super().__str__()
+
+
+class FormError(DNSException):
+ """DNS message is malformed."""
+
+
+class SyntaxError(DNSException):
+ """Text input is malformed."""
+
+
+class UnexpectedEnd(SyntaxError):
+ """Text input ended unexpectedly."""
+
+
+class TooBig(DNSException):
+ """The DNS message is too big."""
+
+
+class Timeout(DNSException):
+ """The DNS operation timed out."""
+
+ supp_kwargs = {"timeout"}
+ fmt = "The DNS operation timed out after {timeout:.3f} seconds"
+
+ # We do this as otherwise mypy complains about unexpected keyword argument
+ # idna_exception
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+
+class UnsupportedAlgorithm(DNSException):
+ """The DNSSEC algorithm is not supported."""
+
+
+class AlgorithmKeyMismatch(UnsupportedAlgorithm):
+ """The DNSSEC algorithm is not supported for the given key type."""
+
+
+class ValidationFailure(DNSException):
+ """The DNSSEC signature is invalid."""
+
+
+class DeniedByPolicy(DNSException):
+ """Denied by DNSSEC policy."""
+
+
+class ExceptionWrapper:
+ def __init__(self, exception_class):
+ self.exception_class = exception_class
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if exc_type is not None and not isinstance(exc_val, self.exception_class):
+ raise self.exception_class(str(exc_val)) from exc_val
+ return False
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/flags.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/flags.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c60be1330b789a9a727fd943a59b44c9b8b8107
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/flags.py
@@ -0,0 +1,123 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Message Flags."""
+
+import enum
+from typing import Any
+
+# Standard DNS flags
+
+
+class Flag(enum.IntFlag):
+ #: Query Response
+ QR = 0x8000
+ #: Authoritative Answer
+ AA = 0x0400
+ #: Truncated Response
+ TC = 0x0200
+ #: Recursion Desired
+ RD = 0x0100
+ #: Recursion Available
+ RA = 0x0080
+ #: Authentic Data
+ AD = 0x0020
+ #: Checking Disabled
+ CD = 0x0010
+
+
+# EDNS flags
+
+
+class EDNSFlag(enum.IntFlag):
+ #: DNSSEC answer OK
+ DO = 0x8000
+
+
+def _from_text(text: str, enum_class: Any) -> int:
+ flags = 0
+ tokens = text.split()
+ for t in tokens:
+ flags |= enum_class[t.upper()]
+ return flags
+
+
+def _to_text(flags: int, enum_class: Any) -> str:
+ text_flags = []
+ for k, v in enum_class.__members__.items():
+ if flags & v != 0:
+ text_flags.append(k)
+ return " ".join(text_flags)
+
+
+def from_text(text: str) -> int:
+ """Convert a space-separated list of flag text values into a flags
+ value.
+
+ Returns an ``int``
+ """
+
+ return _from_text(text, Flag)
+
+
+def to_text(flags: int) -> str:
+ """Convert a flags value into a space-separated list of flag text
+ values.
+
+ Returns a ``str``.
+ """
+
+ return _to_text(flags, Flag)
+
+
+def edns_from_text(text: str) -> int:
+ """Convert a space-separated list of EDNS flag text values into a EDNS
+ flags value.
+
+ Returns an ``int``
+ """
+
+ return _from_text(text, EDNSFlag)
+
+
+def edns_to_text(flags: int) -> str:
+ """Convert an EDNS flags value into a space-separated list of EDNS flag
+ text values.
+
+ Returns a ``str``.
+ """
+
+ return _to_text(flags, EDNSFlag)
+
+
+### BEGIN generated Flag constants
+
+QR = Flag.QR
+AA = Flag.AA
+TC = Flag.TC
+RD = Flag.RD
+RA = Flag.RA
+AD = Flag.AD
+CD = Flag.CD
+
+### END generated Flag constants
+
+### BEGIN generated EDNSFlag constants
+
+DO = EDNSFlag.DO
+
+### END generated EDNSFlag constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/grange.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/grange.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a52278febf1302462e24ca5ece733492b55f096
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/grange.py
@@ -0,0 +1,72 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2012-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS GENERATE range conversion."""
+
+from typing import Tuple
+
+import dns
+
+
+def from_text(text: str) -> Tuple[int, int, int]:
+ """Convert the text form of a range in a ``$GENERATE`` statement to an
+ integer.
+
+ *text*, a ``str``, the textual range in ``$GENERATE`` form.
+
+ Returns a tuple of three ``int`` values ``(start, stop, step)``.
+ """
+
+ start = -1
+ stop = -1
+ step = 1
+ cur = ""
+ state = 0
+ # state 0 1 2
+ # x - y / z
+
+ if text and text[0] == "-":
+ raise dns.exception.SyntaxError("Start cannot be a negative number")
+
+ for c in text:
+ if c == "-" and state == 0:
+ start = int(cur)
+ cur = ""
+ state = 1
+ elif c == "/":
+ stop = int(cur)
+ cur = ""
+ state = 2
+ elif c.isdigit():
+ cur += c
+ else:
+ raise dns.exception.SyntaxError("Could not parse %s" % (c))
+
+ if state == 0:
+ raise dns.exception.SyntaxError("no stop value specified")
+ elif state == 1:
+ stop = int(cur)
+ else:
+ assert state == 2
+ step = int(cur)
+
+ assert step >= 1
+ assert start >= 0
+ if start > stop:
+ raise dns.exception.SyntaxError("start must be <= stop")
+
+ return (start, stop, step)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/immutable.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/immutable.py
new file mode 100644
index 0000000000000000000000000000000000000000..36b0362c75199bc1565ec7a8a2c76bbfa34c3637
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/immutable.py
@@ -0,0 +1,68 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+import collections.abc
+from typing import Any, Callable
+
+from dns._immutable_ctx import immutable
+
+
+@immutable
+class Dict(collections.abc.Mapping): # lgtm[py/missing-equals]
+ def __init__(
+ self,
+ dictionary: Any,
+ no_copy: bool = False,
+ map_factory: Callable[[], collections.abc.MutableMapping] = dict,
+ ):
+ """Make an immutable dictionary from the specified dictionary.
+
+ If *no_copy* is `True`, then *dictionary* will be wrapped instead
+ of copied. Only set this if you are sure there will be no external
+ references to the dictionary.
+ """
+ if no_copy and isinstance(dictionary, collections.abc.MutableMapping):
+ self._odict = dictionary
+ else:
+ self._odict = map_factory()
+ self._odict.update(dictionary)
+ self._hash = None
+
+ def __getitem__(self, key):
+ return self._odict.__getitem__(key)
+
+ def __hash__(self): # pylint: disable=invalid-hash-returned
+ if self._hash is None:
+ h = 0
+ for key in sorted(self._odict.keys()):
+ h ^= hash(key)
+ object.__setattr__(self, "_hash", h)
+ # this does return an int, but pylint doesn't figure that out
+ return self._hash
+
+ def __len__(self):
+ return len(self._odict)
+
+ def __iter__(self):
+ return iter(self._odict)
+
+
+def constify(o: Any) -> Any:
+ """
+ Convert mutable types to immutable types.
+ """
+ if isinstance(o, bytearray):
+ return bytes(o)
+ if isinstance(o, tuple):
+ try:
+ hash(o)
+ return o
+ except Exception:
+ return tuple(constify(elt) for elt in o)
+ if isinstance(o, list):
+ return tuple(constify(elt) for elt in o)
+ if isinstance(o, dict):
+ cdict = dict()
+ for k, v in o.items():
+ cdict[k] = constify(v)
+ return Dict(cdict, True)
+ return o
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/inet.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/inet.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a03f99622d8248e8318c174b85029169522d894
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/inet.py
@@ -0,0 +1,197 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Generic Internet address helper functions."""
+
+import socket
+from typing import Any, Optional, Tuple
+
+import dns.ipv4
+import dns.ipv6
+
+# We assume that AF_INET and AF_INET6 are always defined. We keep
+# these here for the benefit of any old code (unlikely though that
+# is!).
+AF_INET = socket.AF_INET
+AF_INET6 = socket.AF_INET6
+
+
+def inet_pton(family: int, text: str) -> bytes:
+ """Convert the textual form of a network address into its binary form.
+
+ *family* is an ``int``, the address family.
+
+ *text* is a ``str``, the textual address.
+
+ Raises ``NotImplementedError`` if the address family specified is not
+ implemented.
+
+ Returns a ``bytes``.
+ """
+
+ if family == AF_INET:
+ return dns.ipv4.inet_aton(text)
+ elif family == AF_INET6:
+ return dns.ipv6.inet_aton(text, True)
+ else:
+ raise NotImplementedError
+
+
+def inet_ntop(family: int, address: bytes) -> str:
+ """Convert the binary form of a network address into its textual form.
+
+ *family* is an ``int``, the address family.
+
+ *address* is a ``bytes``, the network address in binary form.
+
+ Raises ``NotImplementedError`` if the address family specified is not
+ implemented.
+
+ Returns a ``str``.
+ """
+
+ if family == AF_INET:
+ return dns.ipv4.inet_ntoa(address)
+ elif family == AF_INET6:
+ return dns.ipv6.inet_ntoa(address)
+ else:
+ raise NotImplementedError
+
+
+def af_for_address(text: str) -> int:
+ """Determine the address family of a textual-form network address.
+
+ *text*, a ``str``, the textual address.
+
+ Raises ``ValueError`` if the address family cannot be determined
+ from the input.
+
+ Returns an ``int``.
+ """
+
+ try:
+ dns.ipv4.inet_aton(text)
+ return AF_INET
+ except Exception:
+ try:
+ dns.ipv6.inet_aton(text, True)
+ return AF_INET6
+ except Exception:
+ raise ValueError
+
+
+def is_multicast(text: str) -> bool:
+ """Is the textual-form network address a multicast address?
+
+ *text*, a ``str``, the textual address.
+
+ Raises ``ValueError`` if the address family cannot be determined
+ from the input.
+
+ Returns a ``bool``.
+ """
+
+ try:
+ first = dns.ipv4.inet_aton(text)[0]
+ return first >= 224 and first <= 239
+ except Exception:
+ try:
+ first = dns.ipv6.inet_aton(text, True)[0]
+ return first == 255
+ except Exception:
+ raise ValueError
+
+
+def is_address(text: str) -> bool:
+ """Is the specified string an IPv4 or IPv6 address?
+
+ *text*, a ``str``, the textual address.
+
+ Returns a ``bool``.
+ """
+
+ try:
+ dns.ipv4.inet_aton(text)
+ return True
+ except Exception:
+ try:
+ dns.ipv6.inet_aton(text, True)
+ return True
+ except Exception:
+ return False
+
+
+def low_level_address_tuple(
+ high_tuple: Tuple[str, int], af: Optional[int] = None
+) -> Any:
+ """Given a "high-level" address tuple, i.e.
+ an (address, port) return the appropriate "low-level" address tuple
+ suitable for use in socket calls.
+
+ If an *af* other than ``None`` is provided, it is assumed the
+ address in the high-level tuple is valid and has that af. If af
+ is ``None``, then af_for_address will be called.
+ """
+ address, port = high_tuple
+ if af is None:
+ af = af_for_address(address)
+ if af == AF_INET:
+ return (address, port)
+ elif af == AF_INET6:
+ i = address.find("%")
+ if i < 0:
+ # no scope, shortcut!
+ return (address, port, 0, 0)
+ # try to avoid getaddrinfo()
+ addrpart = address[:i]
+ scope = address[i + 1 :]
+ if scope.isdigit():
+ return (addrpart, port, 0, int(scope))
+ try:
+ return (addrpart, port, 0, socket.if_nametoindex(scope))
+ except AttributeError: # pragma: no cover (we can't really test this)
+ ai_flags = socket.AI_NUMERICHOST
+ ((*_, tup), *_) = socket.getaddrinfo(address, port, flags=ai_flags)
+ return tup
+ else:
+ raise NotImplementedError(f"unknown address family {af}")
+
+
+def any_for_af(af):
+ """Return the 'any' address for the specified address family."""
+ if af == socket.AF_INET:
+ return "0.0.0.0"
+ elif af == socket.AF_INET6:
+ return "::"
+ raise NotImplementedError(f"unknown address family {af}")
+
+
+def canonicalize(text: str) -> str:
+ """Verify that *address* is a valid text form IPv4 or IPv6 address and return its
+ canonical text form. IPv6 addresses with scopes are rejected.
+
+ *text*, a ``str``, the address in textual form.
+
+ Raises ``ValueError`` if the text is not valid.
+ """
+ try:
+ return dns.ipv6.canonicalize(text)
+ except Exception:
+ try:
+ return dns.ipv4.canonicalize(text)
+ except Exception:
+ raise ValueError
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ipv4.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ipv4.py
new file mode 100644
index 0000000000000000000000000000000000000000..65ee69c0d7a4f6ce949edc13d2d2d866889ec5ab
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ipv4.py
@@ -0,0 +1,77 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""IPv4 helper functions."""
+
+import struct
+from typing import Union
+
+import dns.exception
+
+
+def inet_ntoa(address: bytes) -> str:
+ """Convert an IPv4 address in binary form to text form.
+
+ *address*, a ``bytes``, the IPv4 address in binary form.
+
+ Returns a ``str``.
+ """
+
+ if len(address) != 4:
+ raise dns.exception.SyntaxError
+ return "%u.%u.%u.%u" % (address[0], address[1], address[2], address[3])
+
+
+def inet_aton(text: Union[str, bytes]) -> bytes:
+ """Convert an IPv4 address in text form to binary form.
+
+ *text*, a ``str`` or ``bytes``, the IPv4 address in textual form.
+
+ Returns a ``bytes``.
+ """
+
+ if not isinstance(text, bytes):
+ btext = text.encode()
+ else:
+ btext = text
+ parts = btext.split(b".")
+ if len(parts) != 4:
+ raise dns.exception.SyntaxError
+ for part in parts:
+ if not part.isdigit():
+ raise dns.exception.SyntaxError
+ if len(part) > 1 and part[0] == ord("0"):
+ # No leading zeros
+ raise dns.exception.SyntaxError
+ try:
+ b = [int(part) for part in parts]
+ return struct.pack("BBBB", *b)
+ except Exception:
+ raise dns.exception.SyntaxError
+
+
+def canonicalize(text: Union[str, bytes]) -> str:
+ """Verify that *address* is a valid text form IPv4 address and return its
+ canonical text form.
+
+ *text*, a ``str`` or ``bytes``, the IPv4 address in textual form.
+
+ Raises ``dns.exception.SyntaxError`` if the text is not valid.
+ """
+ # Note that inet_aton() only accepts canonial form, but we still run through
+ # inet_ntoa() to ensure the output is a str.
+ return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text))
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ipv6.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ipv6.py
new file mode 100644
index 0000000000000000000000000000000000000000..44a1063936891d417cc8e354acd32dc5b9f70eb1
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ipv6.py
@@ -0,0 +1,219 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""IPv6 helper functions."""
+
+import binascii
+import re
+from typing import List, Union
+
+import dns.exception
+import dns.ipv4
+
+_leading_zero = re.compile(r"0+([0-9a-f]+)")
+
+
+def inet_ntoa(address: bytes) -> str:
+ """Convert an IPv6 address in binary form to text form.
+
+ *address*, a ``bytes``, the IPv6 address in binary form.
+
+ Raises ``ValueError`` if the address isn't 16 bytes long.
+ Returns a ``str``.
+ """
+
+ if len(address) != 16:
+ raise ValueError("IPv6 addresses are 16 bytes long")
+ hex = binascii.hexlify(address)
+ chunks = []
+ i = 0
+ l = len(hex)
+ while i < l:
+ chunk = hex[i : i + 4].decode()
+ # strip leading zeros. we do this with an re instead of
+ # with lstrip() because lstrip() didn't support chars until
+ # python 2.2.2
+ m = _leading_zero.match(chunk)
+ if m is not None:
+ chunk = m.group(1)
+ chunks.append(chunk)
+ i += 4
+ #
+ # Compress the longest subsequence of 0-value chunks to ::
+ #
+ best_start = 0
+ best_len = 0
+ start = -1
+ last_was_zero = False
+ for i in range(8):
+ if chunks[i] != "0":
+ if last_was_zero:
+ end = i
+ current_len = end - start
+ if current_len > best_len:
+ best_start = start
+ best_len = current_len
+ last_was_zero = False
+ elif not last_was_zero:
+ start = i
+ last_was_zero = True
+ if last_was_zero:
+ end = 8
+ current_len = end - start
+ if current_len > best_len:
+ best_start = start
+ best_len = current_len
+ if best_len > 1:
+ if best_start == 0 and (best_len == 6 or best_len == 5 and chunks[5] == "ffff"):
+ # We have an embedded IPv4 address
+ if best_len == 6:
+ prefix = "::"
+ else:
+ prefix = "::ffff:"
+ thex = prefix + dns.ipv4.inet_ntoa(address[12:])
+ else:
+ thex = (
+ ":".join(chunks[:best_start])
+ + "::"
+ + ":".join(chunks[best_start + best_len :])
+ )
+ else:
+ thex = ":".join(chunks)
+ return thex
+
+
+_v4_ending = re.compile(rb"(.*):(\d+\.\d+\.\d+\.\d+)$")
+_colon_colon_start = re.compile(rb"::.*")
+_colon_colon_end = re.compile(rb".*::$")
+
+
+def inet_aton(text: Union[str, bytes], ignore_scope: bool = False) -> bytes:
+ """Convert an IPv6 address in text form to binary form.
+
+ *text*, a ``str`` or ``bytes``, the IPv6 address in textual form.
+
+ *ignore_scope*, a ``bool``. If ``True``, a scope will be ignored.
+ If ``False``, the default, it is an error for a scope to be present.
+
+ Returns a ``bytes``.
+ """
+
+ #
+ # Our aim here is not something fast; we just want something that works.
+ #
+ if not isinstance(text, bytes):
+ btext = text.encode()
+ else:
+ btext = text
+
+ if ignore_scope:
+ parts = btext.split(b"%")
+ l = len(parts)
+ if l == 2:
+ btext = parts[0]
+ elif l > 2:
+ raise dns.exception.SyntaxError
+
+ if btext == b"":
+ raise dns.exception.SyntaxError
+ elif btext.endswith(b":") and not btext.endswith(b"::"):
+ raise dns.exception.SyntaxError
+ elif btext.startswith(b":") and not btext.startswith(b"::"):
+ raise dns.exception.SyntaxError
+ elif btext == b"::":
+ btext = b"0::"
+ #
+ # Get rid of the icky dot-quad syntax if we have it.
+ #
+ m = _v4_ending.match(btext)
+ if m is not None:
+ b = dns.ipv4.inet_aton(m.group(2))
+ btext = (
+ "{}:{:02x}{:02x}:{:02x}{:02x}".format(
+ m.group(1).decode(), b[0], b[1], b[2], b[3]
+ )
+ ).encode()
+ #
+ # Try to turn '::' into ':'; if no match try to
+ # turn '::' into ':'
+ #
+ m = _colon_colon_start.match(btext)
+ if m is not None:
+ btext = btext[1:]
+ else:
+ m = _colon_colon_end.match(btext)
+ if m is not None:
+ btext = btext[:-1]
+ #
+ # Now canonicalize into 8 chunks of 4 hex digits each
+ #
+ chunks = btext.split(b":")
+ l = len(chunks)
+ if l > 8:
+ raise dns.exception.SyntaxError
+ seen_empty = False
+ canonical: List[bytes] = []
+ for c in chunks:
+ if c == b"":
+ if seen_empty:
+ raise dns.exception.SyntaxError
+ seen_empty = True
+ for _ in range(0, 8 - l + 1):
+ canonical.append(b"0000")
+ else:
+ lc = len(c)
+ if lc > 4:
+ raise dns.exception.SyntaxError
+ if lc != 4:
+ c = (b"0" * (4 - lc)) + c
+ canonical.append(c)
+ if l < 8 and not seen_empty:
+ raise dns.exception.SyntaxError
+ btext = b"".join(canonical)
+
+ #
+ # Finally we can go to binary.
+ #
+ try:
+ return binascii.unhexlify(btext)
+ except (binascii.Error, TypeError):
+ raise dns.exception.SyntaxError
+
+
+_mapped_prefix = b"\x00" * 10 + b"\xff\xff"
+
+
+def is_mapped(address: bytes) -> bool:
+ """Is the specified address a mapped IPv4 address?
+
+ *address*, a ``bytes`` is an IPv6 address in binary form.
+
+ Returns a ``bool``.
+ """
+
+ return address.startswith(_mapped_prefix)
+
+
+def canonicalize(text: Union[str, bytes]) -> str:
+ """Verify that *address* is a valid text form IPv6 address and return its
+ canonical text form. Addresses with scopes are rejected.
+
+ *text*, a ``str`` or ``bytes``, the IPv6 address in textual form.
+
+ Raises ``dns.exception.SyntaxError`` if the text is not valid.
+ """
+ return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text))
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/message.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/message.py
new file mode 100644
index 0000000000000000000000000000000000000000..44cacbd9c0a8f85c820247e7b765c3ddb8b3ec3e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/message.py
@@ -0,0 +1,1888 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Messages"""
+
+import contextlib
+import io
+import time
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import dns.edns
+import dns.entropy
+import dns.enum
+import dns.exception
+import dns.flags
+import dns.name
+import dns.opcode
+import dns.rcode
+import dns.rdata
+import dns.rdataclass
+import dns.rdatatype
+import dns.rdtypes.ANY.OPT
+import dns.rdtypes.ANY.TSIG
+import dns.renderer
+import dns.rrset
+import dns.tsig
+import dns.ttl
+import dns.wire
+
+
+class ShortHeader(dns.exception.FormError):
+ """The DNS packet passed to from_wire() is too short."""
+
+
+class TrailingJunk(dns.exception.FormError):
+ """The DNS packet passed to from_wire() has extra junk at the end of it."""
+
+
+class UnknownHeaderField(dns.exception.DNSException):
+ """The header field name was not recognized when converting from text
+ into a message."""
+
+
+class BadEDNS(dns.exception.FormError):
+ """An OPT record occurred somewhere other than
+ the additional data section."""
+
+
+class BadTSIG(dns.exception.FormError):
+ """A TSIG record occurred somewhere other than the end of
+ the additional data section."""
+
+
+class UnknownTSIGKey(dns.exception.DNSException):
+ """A TSIG with an unknown key was received."""
+
+
+class Truncated(dns.exception.DNSException):
+ """The truncated flag is set."""
+
+ supp_kwargs = {"message"}
+
+ # We do this as otherwise mypy complains about unexpected keyword argument
+ # idna_exception
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def message(self):
+ """As much of the message as could be processed.
+
+ Returns a ``dns.message.Message``.
+ """
+ return self.kwargs["message"]
+
+
+class NotQueryResponse(dns.exception.DNSException):
+ """Message is not a response to a query."""
+
+
+class ChainTooLong(dns.exception.DNSException):
+ """The CNAME chain is too long."""
+
+
+class AnswerForNXDOMAIN(dns.exception.DNSException):
+ """The rcode is NXDOMAIN but an answer was found."""
+
+
+class NoPreviousName(dns.exception.SyntaxError):
+ """No previous name was known."""
+
+
+class MessageSection(dns.enum.IntEnum):
+ """Message sections"""
+
+ QUESTION = 0
+ ANSWER = 1
+ AUTHORITY = 2
+ ADDITIONAL = 3
+
+ @classmethod
+ def _maximum(cls):
+ return 3
+
+
+class MessageError:
+ def __init__(self, exception: Exception, offset: int):
+ self.exception = exception
+ self.offset = offset
+
+
+DEFAULT_EDNS_PAYLOAD = 1232
+MAX_CHAIN = 16
+
+IndexKeyType = Tuple[
+ int,
+ dns.name.Name,
+ dns.rdataclass.RdataClass,
+ dns.rdatatype.RdataType,
+ Optional[dns.rdatatype.RdataType],
+ Optional[dns.rdataclass.RdataClass],
+]
+IndexType = Dict[IndexKeyType, dns.rrset.RRset]
+SectionType = Union[int, str, List[dns.rrset.RRset]]
+
+
+class Message:
+ """A DNS message."""
+
+ _section_enum = MessageSection
+
+ def __init__(self, id: Optional[int] = None):
+ if id is None:
+ self.id = dns.entropy.random_16()
+ else:
+ self.id = id
+ self.flags = 0
+ self.sections: List[List[dns.rrset.RRset]] = [[], [], [], []]
+ self.opt: Optional[dns.rrset.RRset] = None
+ self.request_payload = 0
+ self.pad = 0
+ self.keyring: Any = None
+ self.tsig: Optional[dns.rrset.RRset] = None
+ self.request_mac = b""
+ self.xfr = False
+ self.origin: Optional[dns.name.Name] = None
+ self.tsig_ctx: Optional[Any] = None
+ self.index: IndexType = {}
+ self.errors: List[MessageError] = []
+ self.time = 0.0
+
+ @property
+ def question(self) -> List[dns.rrset.RRset]:
+ """The question section."""
+ return self.sections[0]
+
+ @question.setter
+ def question(self, v):
+ self.sections[0] = v
+
+ @property
+ def answer(self) -> List[dns.rrset.RRset]:
+ """The answer section."""
+ return self.sections[1]
+
+ @answer.setter
+ def answer(self, v):
+ self.sections[1] = v
+
+ @property
+ def authority(self) -> List[dns.rrset.RRset]:
+ """The authority section."""
+ return self.sections[2]
+
+ @authority.setter
+ def authority(self, v):
+ self.sections[2] = v
+
+ @property
+ def additional(self) -> List[dns.rrset.RRset]:
+ """The additional data section."""
+ return self.sections[3]
+
+ @additional.setter
+ def additional(self, v):
+ self.sections[3] = v
+
+ def __repr__(self):
+ return ""
+
+ def __str__(self):
+ return self.to_text()
+
+ def to_text(
+ self,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ **kw: Dict[str, Any],
+ ) -> str:
+ """Convert the message to text.
+
+ The *origin*, *relativize*, and any other keyword
+ arguments are passed to the RRset ``to_wire()`` method.
+
+ Returns a ``str``.
+ """
+
+ s = io.StringIO()
+ s.write("id %d\n" % self.id)
+ s.write("opcode %s\n" % dns.opcode.to_text(self.opcode()))
+ s.write("rcode %s\n" % dns.rcode.to_text(self.rcode()))
+ s.write("flags %s\n" % dns.flags.to_text(self.flags))
+ if self.edns >= 0:
+ s.write("edns %s\n" % self.edns)
+ if self.ednsflags != 0:
+ s.write("eflags %s\n" % dns.flags.edns_to_text(self.ednsflags))
+ s.write("payload %d\n" % self.payload)
+ for opt in self.options:
+ s.write("option %s\n" % opt.to_text())
+ for name, which in self._section_enum.__members__.items():
+ s.write(f";{name}\n")
+ for rrset in self.section_from_number(which):
+ s.write(rrset.to_text(origin, relativize, **kw))
+ s.write("\n")
+ #
+ # We strip off the final \n so the caller can print the result without
+ # doing weird things to get around eccentricities in Python print
+ # formatting
+ #
+ return s.getvalue()[:-1]
+
+ def __eq__(self, other):
+ """Two messages are equal if they have the same content in the
+ header, question, answer, and authority sections.
+
+ Returns a ``bool``.
+ """
+
+ if not isinstance(other, Message):
+ return False
+ if self.id != other.id:
+ return False
+ if self.flags != other.flags:
+ return False
+ for i, section in enumerate(self.sections):
+ other_section = other.sections[i]
+ for n in section:
+ if n not in other_section:
+ return False
+ for n in other_section:
+ if n not in section:
+ return False
+ return True
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def is_response(self, other: "Message") -> bool:
+ """Is *other*, also a ``dns.message.Message``, a response to this
+ message?
+
+ Returns a ``bool``.
+ """
+
+ if (
+ other.flags & dns.flags.QR == 0
+ or self.id != other.id
+ or dns.opcode.from_flags(self.flags) != dns.opcode.from_flags(other.flags)
+ ):
+ return False
+ if other.rcode() in {
+ dns.rcode.FORMERR,
+ dns.rcode.SERVFAIL,
+ dns.rcode.NOTIMP,
+ dns.rcode.REFUSED,
+ }:
+ # We don't check the question section in these cases if
+ # the other question section is empty, even though they
+ # still really ought to have a question section.
+ if len(other.question) == 0:
+ return True
+ if dns.opcode.is_update(self.flags):
+ # This is assuming the "sender doesn't include anything
+ # from the update", but we don't care to check the other
+ # case, which is that all the sections are returned and
+ # identical.
+ return True
+ for n in self.question:
+ if n not in other.question:
+ return False
+ for n in other.question:
+ if n not in self.question:
+ return False
+ return True
+
+ def section_number(self, section: List[dns.rrset.RRset]) -> int:
+ """Return the "section number" of the specified section for use
+ in indexing.
+
+ *section* is one of the section attributes of this message.
+
+ Raises ``ValueError`` if the section isn't known.
+
+ Returns an ``int``.
+ """
+
+ for i, our_section in enumerate(self.sections):
+ if section is our_section:
+ return self._section_enum(i)
+ raise ValueError("unknown section")
+
+ def section_from_number(self, number: int) -> List[dns.rrset.RRset]:
+ """Return the section list associated with the specified section
+ number.
+
+ *number* is a section number `int` or the text form of a section
+ name.
+
+ Raises ``ValueError`` if the section isn't known.
+
+ Returns a ``list``.
+ """
+
+ section = self._section_enum.make(number)
+ return self.sections[section]
+
+ def find_rrset(
+ self,
+ section: SectionType,
+ name: dns.name.Name,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ deleting: Optional[dns.rdataclass.RdataClass] = None,
+ create: bool = False,
+ force_unique: bool = False,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ ) -> dns.rrset.RRset:
+ """Find the RRset with the given attributes in the specified section.
+
+ *section*, an ``int`` section number, a ``str`` section name, or one of
+ the section attributes of this message. This specifies the
+ the section of the message to search. For example::
+
+ my_message.find_rrset(my_message.answer, name, rdclass, rdtype)
+ my_message.find_rrset(dns.message.ANSWER, name, rdclass, rdtype)
+ my_message.find_rrset("ANSWER", name, rdclass, rdtype)
+
+ *name*, a ``dns.name.Name`` or ``str``, the name of the RRset.
+
+ *rdclass*, an ``int`` or ``str``, the class of the RRset.
+
+ *rdtype*, an ``int`` or ``str``, the type of the RRset.
+
+ *covers*, an ``int`` or ``str``, the covers value of the RRset.
+ The default is ``dns.rdatatype.NONE``.
+
+ *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the
+ RRset. The default is ``None``.
+
+ *create*, a ``bool``. If ``True``, create the RRset if it is not found.
+ The created RRset is appended to *section*.
+
+ *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``,
+ create a new RRset regardless of whether a matching RRset exists
+ already. The default is ``False``. This is useful when creating
+ DDNS Update messages, as order matters for them.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ Raises ``KeyError`` if the RRset was not found and create was
+ ``False``.
+
+ Returns a ``dns.rrset.RRset object``.
+ """
+
+ if isinstance(section, int):
+ section_number = section
+ section = self.section_from_number(section_number)
+ elif isinstance(section, str):
+ section_number = self._section_enum.from_text(section)
+ section = self.section_from_number(section_number)
+ else:
+ section_number = self.section_number(section)
+ if isinstance(name, str):
+ name = dns.name.from_text(name, idna_codec=idna_codec)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ covers = dns.rdatatype.RdataType.make(covers)
+ if deleting is not None:
+ deleting = dns.rdataclass.RdataClass.make(deleting)
+ key = (section_number, name, rdclass, rdtype, covers, deleting)
+ if not force_unique:
+ if self.index is not None:
+ rrset = self.index.get(key)
+ if rrset is not None:
+ return rrset
+ else:
+ for rrset in section:
+ if rrset.full_match(name, rdclass, rdtype, covers, deleting):
+ return rrset
+ if not create:
+ raise KeyError
+ rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting)
+ section.append(rrset)
+ if self.index is not None:
+ self.index[key] = rrset
+ return rrset
+
+ def get_rrset(
+ self,
+ section: SectionType,
+ name: dns.name.Name,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ deleting: Optional[dns.rdataclass.RdataClass] = None,
+ create: bool = False,
+ force_unique: bool = False,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ ) -> Optional[dns.rrset.RRset]:
+ """Get the RRset with the given attributes in the specified section.
+
+ If the RRset is not found, None is returned.
+
+ *section*, an ``int`` section number, a ``str`` section name, or one of
+ the section attributes of this message. This specifies the
+ the section of the message to search. For example::
+
+ my_message.get_rrset(my_message.answer, name, rdclass, rdtype)
+ my_message.get_rrset(dns.message.ANSWER, name, rdclass, rdtype)
+ my_message.get_rrset("ANSWER", name, rdclass, rdtype)
+
+ *name*, a ``dns.name.Name`` or ``str``, the name of the RRset.
+
+ *rdclass*, an ``int`` or ``str``, the class of the RRset.
+
+ *rdtype*, an ``int`` or ``str``, the type of the RRset.
+
+ *covers*, an ``int`` or ``str``, the covers value of the RRset.
+ The default is ``dns.rdatatype.NONE``.
+
+ *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the
+ RRset. The default is ``None``.
+
+ *create*, a ``bool``. If ``True``, create the RRset if it is not found.
+ The created RRset is appended to *section*.
+
+ *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``,
+ create a new RRset regardless of whether a matching RRset exists
+ already. The default is ``False``. This is useful when creating
+ DDNS Update messages, as order matters for them.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ Returns a ``dns.rrset.RRset object`` or ``None``.
+ """
+
+ try:
+ rrset = self.find_rrset(
+ section,
+ name,
+ rdclass,
+ rdtype,
+ covers,
+ deleting,
+ create,
+ force_unique,
+ idna_codec,
+ )
+ except KeyError:
+ rrset = None
+ return rrset
+
+ def section_count(self, section: SectionType) -> int:
+ """Returns the number of records in the specified section.
+
+ *section*, an ``int`` section number, a ``str`` section name, or one of
+ the section attributes of this message. This specifies the
+ the section of the message to count. For example::
+
+ my_message.section_count(my_message.answer)
+ my_message.section_count(dns.message.ANSWER)
+ my_message.section_count("ANSWER")
+ """
+
+ if isinstance(section, int):
+ section_number = section
+ section = self.section_from_number(section_number)
+ elif isinstance(section, str):
+ section_number = self._section_enum.from_text(section)
+ section = self.section_from_number(section_number)
+ else:
+ section_number = self.section_number(section)
+ count = sum(max(1, len(rrs)) for rrs in section)
+ if section_number == MessageSection.ADDITIONAL:
+ if self.opt is not None:
+ count += 1
+ if self.tsig is not None:
+ count += 1
+ return count
+
+ def _compute_opt_reserve(self) -> int:
+ """Compute the size required for the OPT RR, padding excluded"""
+ if not self.opt:
+ return 0
+ # 1 byte for the root name, 10 for the standard RR fields
+ size = 11
+ # This would be more efficient if options had a size() method, but we won't
+ # worry about that for now. We also don't worry if there is an existing padding
+ # option, as it is unlikely and probably harmless, as the worst case is that we
+ # may add another, and this seems to be legal.
+ for option in self.opt[0].options:
+ wire = option.to_wire()
+ # We add 4 here to account for the option type and length
+ size += len(wire) + 4
+ if self.pad:
+ # Padding will be added, so again add the option type and length.
+ size += 4
+ return size
+
+ def _compute_tsig_reserve(self) -> int:
+ """Compute the size required for the TSIG RR"""
+ # This would be more efficient if TSIGs had a size method, but we won't
+ # worry about for now. Also, we can't really cope with the potential
+ # compressibility of the TSIG owner name, so we estimate with the uncompressed
+ # size. We will disable compression when TSIG and padding are both is active
+ # so that the padding comes out right.
+ if not self.tsig:
+ return 0
+ f = io.BytesIO()
+ self.tsig.to_wire(f)
+ return len(f.getvalue())
+
+ def to_wire(
+ self,
+ origin: Optional[dns.name.Name] = None,
+ max_size: int = 0,
+ multi: bool = False,
+ tsig_ctx: Optional[Any] = None,
+ prepend_length: bool = False,
+ prefer_truncation: bool = False,
+ **kw: Dict[str, Any],
+ ) -> bytes:
+ """Return a string containing the message in DNS compressed wire
+ format.
+
+ Additional keyword arguments are passed to the RRset ``to_wire()``
+ method.
+
+ *origin*, a ``dns.name.Name`` or ``None``, the origin to be appended
+ to any relative names. If ``None``, and the message has an origin
+ attribute that is not ``None``, then it will be used.
+
+ *max_size*, an ``int``, the maximum size of the wire format
+ output; default is 0, which means "the message's request
+ payload, if nonzero, or 65535".
+
+ *multi*, a ``bool``, should be set to ``True`` if this message is
+ part of a multiple message sequence.
+
+ *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the
+ ongoing TSIG context, used when signing zone transfers.
+
+ *prepend_length*, a ``bool``, should be set to ``True`` if the caller
+ wants the message length prepended to the message itself. This is
+ useful for messages sent over TCP, TLS (DoT), or QUIC (DoQ).
+
+ *prefer_truncation*, a ``bool``, should be set to ``True`` if the caller
+ wants the message to be truncated if it would otherwise exceed the
+ maximum length. If the truncation occurs before the additional section,
+ the TC bit will be set.
+
+ Raises ``dns.exception.TooBig`` if *max_size* was exceeded.
+
+ Returns a ``bytes``.
+ """
+
+ if origin is None and self.origin is not None:
+ origin = self.origin
+ if max_size == 0:
+ if self.request_payload != 0:
+ max_size = self.request_payload
+ else:
+ max_size = 65535
+ if max_size < 512:
+ max_size = 512
+ elif max_size > 65535:
+ max_size = 65535
+ r = dns.renderer.Renderer(self.id, self.flags, max_size, origin)
+ opt_reserve = self._compute_opt_reserve()
+ r.reserve(opt_reserve)
+ tsig_reserve = self._compute_tsig_reserve()
+ r.reserve(tsig_reserve)
+ try:
+ for rrset in self.question:
+ r.add_question(rrset.name, rrset.rdtype, rrset.rdclass)
+ for rrset in self.answer:
+ r.add_rrset(dns.renderer.ANSWER, rrset, **kw)
+ for rrset in self.authority:
+ r.add_rrset(dns.renderer.AUTHORITY, rrset, **kw)
+ for rrset in self.additional:
+ r.add_rrset(dns.renderer.ADDITIONAL, rrset, **kw)
+ except dns.exception.TooBig:
+ if prefer_truncation:
+ if r.section < dns.renderer.ADDITIONAL:
+ r.flags |= dns.flags.TC
+ else:
+ raise
+ r.release_reserved()
+ if self.opt is not None:
+ r.add_opt(self.opt, self.pad, opt_reserve, tsig_reserve)
+ r.write_header()
+ if self.tsig is not None:
+ (new_tsig, ctx) = dns.tsig.sign(
+ r.get_wire(),
+ self.keyring,
+ self.tsig[0],
+ int(time.time()),
+ self.request_mac,
+ tsig_ctx,
+ multi,
+ )
+ self.tsig.clear()
+ self.tsig.add(new_tsig)
+ r.add_rrset(dns.renderer.ADDITIONAL, self.tsig)
+ r.write_header()
+ if multi:
+ self.tsig_ctx = ctx
+ wire = r.get_wire()
+ if prepend_length:
+ wire = len(wire).to_bytes(2, "big") + wire
+ return wire
+
+ @staticmethod
+ def _make_tsig(
+ keyname, algorithm, time_signed, fudge, mac, original_id, error, other
+ ):
+ tsig = dns.rdtypes.ANY.TSIG.TSIG(
+ dns.rdataclass.ANY,
+ dns.rdatatype.TSIG,
+ algorithm,
+ time_signed,
+ fudge,
+ mac,
+ original_id,
+ error,
+ other,
+ )
+ return dns.rrset.from_rdata(keyname, 0, tsig)
+
+ def use_tsig(
+ self,
+ keyring: Any,
+ keyname: Optional[Union[dns.name.Name, str]] = None,
+ fudge: int = 300,
+ original_id: Optional[int] = None,
+ tsig_error: int = 0,
+ other_data: bytes = b"",
+ algorithm: Union[dns.name.Name, str] = dns.tsig.default_algorithm,
+ ) -> None:
+ """When sending, a TSIG signature using the specified key
+ should be added.
+
+ *key*, a ``dns.tsig.Key`` is the key to use. If a key is specified,
+ the *keyring* and *algorithm* fields are not used.
+
+ *keyring*, a ``dict``, ``callable`` or ``dns.tsig.Key``, is either
+ the TSIG keyring or key to use.
+
+ The format of a keyring dict is a mapping from TSIG key name, as
+ ``dns.name.Name`` to ``dns.tsig.Key`` or a TSIG secret, a ``bytes``.
+ If a ``dict`` *keyring* is specified but a *keyname* is not, the key
+ used will be the first key in the *keyring*. Note that the order of
+ keys in a dictionary is not defined, so applications should supply a
+ keyname when a ``dict`` keyring is used, unless they know the keyring
+ contains only one key. If a ``callable`` keyring is specified, the
+ callable will be called with the message and the keyname, and is
+ expected to return a key.
+
+ *keyname*, a ``dns.name.Name``, ``str`` or ``None``, the name of
+ this TSIG key to use; defaults to ``None``. If *keyring* is a
+ ``dict``, the key must be defined in it. If *keyring* is a
+ ``dns.tsig.Key``, this is ignored.
+
+ *fudge*, an ``int``, the TSIG time fudge.
+
+ *original_id*, an ``int``, the TSIG original id. If ``None``,
+ the message's id is used.
+
+ *tsig_error*, an ``int``, the TSIG error code.
+
+ *other_data*, a ``bytes``, the TSIG other data.
+
+ *algorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use. This is
+ only used if *keyring* is a ``dict``, and the key entry is a ``bytes``.
+ """
+
+ if isinstance(keyring, dns.tsig.Key):
+ key = keyring
+ keyname = key.name
+ elif callable(keyring):
+ key = keyring(self, keyname)
+ else:
+ if isinstance(keyname, str):
+ keyname = dns.name.from_text(keyname)
+ if keyname is None:
+ keyname = next(iter(keyring))
+ key = keyring[keyname]
+ if isinstance(key, bytes):
+ key = dns.tsig.Key(keyname, key, algorithm)
+ self.keyring = key
+ if original_id is None:
+ original_id = self.id
+ self.tsig = self._make_tsig(
+ keyname,
+ self.keyring.algorithm,
+ 0,
+ fudge,
+ b"\x00" * dns.tsig.mac_sizes[self.keyring.algorithm],
+ original_id,
+ tsig_error,
+ other_data,
+ )
+
+ @property
+ def keyname(self) -> Optional[dns.name.Name]:
+ if self.tsig:
+ return self.tsig.name
+ else:
+ return None
+
+ @property
+ def keyalgorithm(self) -> Optional[dns.name.Name]:
+ if self.tsig:
+ return self.tsig[0].algorithm
+ else:
+ return None
+
+ @property
+ def mac(self) -> Optional[bytes]:
+ if self.tsig:
+ return self.tsig[0].mac
+ else:
+ return None
+
+ @property
+ def tsig_error(self) -> Optional[int]:
+ if self.tsig:
+ return self.tsig[0].error
+ else:
+ return None
+
+ @property
+ def had_tsig(self) -> bool:
+ return bool(self.tsig)
+
+ @staticmethod
+ def _make_opt(flags=0, payload=DEFAULT_EDNS_PAYLOAD, options=None):
+ opt = dns.rdtypes.ANY.OPT.OPT(payload, dns.rdatatype.OPT, options or ())
+ return dns.rrset.from_rdata(dns.name.root, int(flags), opt)
+
+ def use_edns(
+ self,
+ edns: Optional[Union[int, bool]] = 0,
+ ednsflags: int = 0,
+ payload: int = DEFAULT_EDNS_PAYLOAD,
+ request_payload: Optional[int] = None,
+ options: Optional[List[dns.edns.Option]] = None,
+ pad: int = 0,
+ ) -> None:
+ """Configure EDNS behavior.
+
+ *edns*, an ``int``, is the EDNS level to use. Specifying ``None``, ``False``,
+ or ``-1`` means "do not use EDNS", and in this case the other parameters are
+ ignored. Specifying ``True`` is equivalent to specifying 0, i.e. "use EDNS0".
+
+ *ednsflags*, an ``int``, the EDNS flag values.
+
+ *payload*, an ``int``, is the EDNS sender's payload field, which is the maximum
+ size of UDP datagram the sender can handle. I.e. how big a response to this
+ message can be.
+
+ *request_payload*, an ``int``, is the EDNS payload size to use when sending this
+ message. If not specified, defaults to the value of *payload*.
+
+ *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS options.
+
+ *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add
+ padding bytes to make the message size a multiple of *pad*. Note that if
+ padding is non-zero, an EDNS PADDING option will always be added to the
+ message.
+ """
+
+ if edns is None or edns is False:
+ edns = -1
+ elif edns is True:
+ edns = 0
+ if edns < 0:
+ self.opt = None
+ self.request_payload = 0
+ else:
+ # make sure the EDNS version in ednsflags agrees with edns
+ ednsflags &= 0xFF00FFFF
+ ednsflags |= edns << 16
+ if options is None:
+ options = []
+ self.opt = self._make_opt(ednsflags, payload, options)
+ if request_payload is None:
+ request_payload = payload
+ self.request_payload = request_payload
+ if pad < 0:
+ raise ValueError("pad must be non-negative")
+ self.pad = pad
+
+ @property
+ def edns(self) -> int:
+ if self.opt:
+ return (self.ednsflags & 0xFF0000) >> 16
+ else:
+ return -1
+
+ @property
+ def ednsflags(self) -> int:
+ if self.opt:
+ return self.opt.ttl
+ else:
+ return 0
+
+ @ednsflags.setter
+ def ednsflags(self, v):
+ if self.opt:
+ self.opt.ttl = v
+ elif v:
+ self.opt = self._make_opt(v)
+
+ @property
+ def payload(self) -> int:
+ if self.opt:
+ return self.opt[0].payload
+ else:
+ return 0
+
+ @property
+ def options(self) -> Tuple:
+ if self.opt:
+ return self.opt[0].options
+ else:
+ return ()
+
+ def want_dnssec(self, wanted: bool = True) -> None:
+ """Enable or disable 'DNSSEC desired' flag in requests.
+
+ *wanted*, a ``bool``. If ``True``, then DNSSEC data is
+ desired in the response, EDNS is enabled if required, and then
+ the DO bit is set. If ``False``, the DO bit is cleared if
+ EDNS is enabled.
+ """
+
+ if wanted:
+ self.ednsflags |= dns.flags.DO
+ elif self.opt:
+ self.ednsflags &= ~int(dns.flags.DO)
+
+ def rcode(self) -> dns.rcode.Rcode:
+ """Return the rcode.
+
+ Returns a ``dns.rcode.Rcode``.
+ """
+ return dns.rcode.from_flags(int(self.flags), int(self.ednsflags))
+
+ def set_rcode(self, rcode: dns.rcode.Rcode) -> None:
+ """Set the rcode.
+
+ *rcode*, a ``dns.rcode.Rcode``, is the rcode to set.
+ """
+ (value, evalue) = dns.rcode.to_flags(rcode)
+ self.flags &= 0xFFF0
+ self.flags |= value
+ self.ednsflags &= 0x00FFFFFF
+ self.ednsflags |= evalue
+
+ def opcode(self) -> dns.opcode.Opcode:
+ """Return the opcode.
+
+ Returns a ``dns.opcode.Opcode``.
+ """
+ return dns.opcode.from_flags(int(self.flags))
+
+ def set_opcode(self, opcode: dns.opcode.Opcode) -> None:
+ """Set the opcode.
+
+ *opcode*, a ``dns.opcode.Opcode``, is the opcode to set.
+ """
+ self.flags &= 0x87FF
+ self.flags |= dns.opcode.to_flags(opcode)
+
+ def _get_one_rr_per_rrset(self, value):
+ # What the caller picked is fine.
+ return value
+
+ # pylint: disable=unused-argument
+
+ def _parse_rr_header(self, section, name, rdclass, rdtype):
+ return (rdclass, rdtype, None, False)
+
+ # pylint: enable=unused-argument
+
+ def _parse_special_rr_header(self, section, count, position, name, rdclass, rdtype):
+ if rdtype == dns.rdatatype.OPT:
+ if (
+ section != MessageSection.ADDITIONAL
+ or self.opt
+ or name != dns.name.root
+ ):
+ raise BadEDNS
+ elif rdtype == dns.rdatatype.TSIG:
+ if (
+ section != MessageSection.ADDITIONAL
+ or rdclass != dns.rdatatype.ANY
+ or position != count - 1
+ ):
+ raise BadTSIG
+ return (rdclass, rdtype, None, False)
+
+
+class ChainingResult:
+ """The result of a call to dns.message.QueryMessage.resolve_chaining().
+
+ The ``answer`` attribute is the answer RRSet, or ``None`` if it doesn't
+ exist.
+
+ The ``canonical_name`` attribute is the canonical name after all
+ chaining has been applied (this is the same name as ``rrset.name`` in cases
+ where rrset is not ``None``).
+
+ The ``minimum_ttl`` attribute is the minimum TTL, i.e. the TTL to
+ use if caching the data. It is the smallest of all the CNAME TTLs
+ and either the answer TTL if it exists or the SOA TTL and SOA
+ minimum values for negative answers.
+
+ The ``cnames`` attribute is a list of all the CNAME RRSets followed to
+ get to the canonical name.
+ """
+
+ def __init__(
+ self,
+ canonical_name: dns.name.Name,
+ answer: Optional[dns.rrset.RRset],
+ minimum_ttl: int,
+ cnames: List[dns.rrset.RRset],
+ ):
+ self.canonical_name = canonical_name
+ self.answer = answer
+ self.minimum_ttl = minimum_ttl
+ self.cnames = cnames
+
+
+class QueryMessage(Message):
+ def resolve_chaining(self) -> ChainingResult:
+ """Follow the CNAME chain in the response to determine the answer
+ RRset.
+
+ Raises ``dns.message.NotQueryResponse`` if the message is not
+ a response.
+
+ Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long.
+
+ Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN
+ but an answer was found.
+
+ Raises ``dns.exception.FormError`` if the question count is not 1.
+
+ Returns a ChainingResult object.
+ """
+ if self.flags & dns.flags.QR == 0:
+ raise NotQueryResponse
+ if len(self.question) != 1:
+ raise dns.exception.FormError
+ question = self.question[0]
+ qname = question.name
+ min_ttl = dns.ttl.MAX_TTL
+ answer = None
+ count = 0
+ cnames = []
+ while count < MAX_CHAIN:
+ try:
+ answer = self.find_rrset(
+ self.answer, qname, question.rdclass, question.rdtype
+ )
+ min_ttl = min(min_ttl, answer.ttl)
+ break
+ except KeyError:
+ if question.rdtype != dns.rdatatype.CNAME:
+ try:
+ crrset = self.find_rrset(
+ self.answer, qname, question.rdclass, dns.rdatatype.CNAME
+ )
+ cnames.append(crrset)
+ min_ttl = min(min_ttl, crrset.ttl)
+ for rd in crrset:
+ qname = rd.target
+ break
+ count += 1
+ continue
+ except KeyError:
+ # Exit the chaining loop
+ break
+ else:
+ # Exit the chaining loop
+ break
+ if count >= MAX_CHAIN:
+ raise ChainTooLong
+ if self.rcode() == dns.rcode.NXDOMAIN and answer is not None:
+ raise AnswerForNXDOMAIN
+ if answer is None:
+ # Further minimize the TTL with NCACHE.
+ auname = qname
+ while True:
+ # Look for an SOA RR whose owner name is a superdomain
+ # of qname.
+ try:
+ srrset = self.find_rrset(
+ self.authority, auname, question.rdclass, dns.rdatatype.SOA
+ )
+ min_ttl = min(min_ttl, srrset.ttl, srrset[0].minimum)
+ break
+ except KeyError:
+ try:
+ auname = auname.parent()
+ except dns.name.NoParent:
+ break
+ return ChainingResult(qname, answer, min_ttl, cnames)
+
+ def canonical_name(self) -> dns.name.Name:
+ """Return the canonical name of the first name in the question
+ section.
+
+ Raises ``dns.message.NotQueryResponse`` if the message is not
+ a response.
+
+ Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long.
+
+ Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN
+ but an answer was found.
+
+ Raises ``dns.exception.FormError`` if the question count is not 1.
+ """
+ return self.resolve_chaining().canonical_name
+
+
+def _maybe_import_update():
+ # We avoid circular imports by doing this here. We do it in another
+ # function as doing it in _message_factory_from_opcode() makes "dns"
+ # a local symbol, and the first line fails :)
+
+ # pylint: disable=redefined-outer-name,import-outside-toplevel,unused-import
+ import dns.update # noqa: F401
+
+
+def _message_factory_from_opcode(opcode):
+ if opcode == dns.opcode.QUERY:
+ return QueryMessage
+ elif opcode == dns.opcode.UPDATE:
+ _maybe_import_update()
+ return dns.update.UpdateMessage
+ else:
+ return Message
+
+
+class _WireReader:
+ """Wire format reader.
+
+ parser: the binary parser
+ message: The message object being built
+ initialize_message: Callback to set message parsing options
+ question_only: Are we only reading the question?
+ one_rr_per_rrset: Put each RR into its own RRset?
+ keyring: TSIG keyring
+ ignore_trailing: Ignore trailing junk at end of request?
+ multi: Is this message part of a multi-message sequence?
+ DNS dynamic updates.
+ continue_on_error: try to extract as much information as possible from
+ the message, accumulating MessageErrors in the *errors* attribute instead of
+ raising them.
+ """
+
+ def __init__(
+ self,
+ wire,
+ initialize_message,
+ question_only=False,
+ one_rr_per_rrset=False,
+ ignore_trailing=False,
+ keyring=None,
+ multi=False,
+ continue_on_error=False,
+ ):
+ self.parser = dns.wire.Parser(wire)
+ self.message = None
+ self.initialize_message = initialize_message
+ self.question_only = question_only
+ self.one_rr_per_rrset = one_rr_per_rrset
+ self.ignore_trailing = ignore_trailing
+ self.keyring = keyring
+ self.multi = multi
+ self.continue_on_error = continue_on_error
+ self.errors = []
+
+ def _get_question(self, section_number, qcount):
+ """Read the next *qcount* records from the wire data and add them to
+ the question section.
+ """
+ assert self.message is not None
+ section = self.message.sections[section_number]
+ for _ in range(qcount):
+ qname = self.parser.get_name(self.message.origin)
+ (rdtype, rdclass) = self.parser.get_struct("!HH")
+ (rdclass, rdtype, _, _) = self.message._parse_rr_header(
+ section_number, qname, rdclass, rdtype
+ )
+ self.message.find_rrset(
+ section, qname, rdclass, rdtype, create=True, force_unique=True
+ )
+
+ def _add_error(self, e):
+ self.errors.append(MessageError(e, self.parser.current))
+
+ def _get_section(self, section_number, count):
+ """Read the next I{count} records from the wire data and add them to
+ the specified section.
+
+ section_number: the section of the message to which to add records
+ count: the number of records to read
+ """
+ assert self.message is not None
+ section = self.message.sections[section_number]
+ force_unique = self.one_rr_per_rrset
+ for i in range(count):
+ rr_start = self.parser.current
+ absolute_name = self.parser.get_name()
+ if self.message.origin is not None:
+ name = absolute_name.relativize(self.message.origin)
+ else:
+ name = absolute_name
+ (rdtype, rdclass, ttl, rdlen) = self.parser.get_struct("!HHIH")
+ if rdtype in (dns.rdatatype.OPT, dns.rdatatype.TSIG):
+ (
+ rdclass,
+ rdtype,
+ deleting,
+ empty,
+ ) = self.message._parse_special_rr_header(
+ section_number, count, i, name, rdclass, rdtype
+ )
+ else:
+ (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header(
+ section_number, name, rdclass, rdtype
+ )
+ rdata_start = self.parser.current
+ try:
+ if empty:
+ if rdlen > 0:
+ raise dns.exception.FormError
+ rd = None
+ covers = dns.rdatatype.NONE
+ else:
+ with self.parser.restrict_to(rdlen):
+ rd = dns.rdata.from_wire_parser(
+ rdclass, rdtype, self.parser, self.message.origin
+ )
+ covers = rd.covers()
+ if self.message.xfr and rdtype == dns.rdatatype.SOA:
+ force_unique = True
+ if rdtype == dns.rdatatype.OPT:
+ self.message.opt = dns.rrset.from_rdata(name, ttl, rd)
+ elif rdtype == dns.rdatatype.TSIG:
+ if self.keyring is None:
+ raise UnknownTSIGKey("got signed message without keyring")
+ if isinstance(self.keyring, dict):
+ key = self.keyring.get(absolute_name)
+ if isinstance(key, bytes):
+ key = dns.tsig.Key(absolute_name, key, rd.algorithm)
+ elif callable(self.keyring):
+ key = self.keyring(self.message, absolute_name)
+ else:
+ key = self.keyring
+ if key is None:
+ raise UnknownTSIGKey("key '%s' unknown" % name)
+ self.message.keyring = key
+ self.message.tsig_ctx = dns.tsig.validate(
+ self.parser.wire,
+ key,
+ absolute_name,
+ rd,
+ int(time.time()),
+ self.message.request_mac,
+ rr_start,
+ self.message.tsig_ctx,
+ self.multi,
+ )
+ self.message.tsig = dns.rrset.from_rdata(absolute_name, 0, rd)
+ else:
+ rrset = self.message.find_rrset(
+ section,
+ name,
+ rdclass,
+ rdtype,
+ covers,
+ deleting,
+ True,
+ force_unique,
+ )
+ if rd is not None:
+ if ttl > 0x7FFFFFFF:
+ ttl = 0
+ rrset.add(rd, ttl)
+ except Exception as e:
+ if self.continue_on_error:
+ self._add_error(e)
+ self.parser.seek(rdata_start + rdlen)
+ else:
+ raise
+
+ def read(self):
+ """Read a wire format DNS message and build a dns.message.Message
+ object."""
+
+ if self.parser.remaining() < 12:
+ raise ShortHeader
+ (id, flags, qcount, ancount, aucount, adcount) = self.parser.get_struct(
+ "!HHHHHH"
+ )
+ factory = _message_factory_from_opcode(dns.opcode.from_flags(flags))
+ self.message = factory(id=id)
+ self.message.flags = dns.flags.Flag(flags)
+ self.initialize_message(self.message)
+ self.one_rr_per_rrset = self.message._get_one_rr_per_rrset(
+ self.one_rr_per_rrset
+ )
+ try:
+ self._get_question(MessageSection.QUESTION, qcount)
+ if self.question_only:
+ return self.message
+ self._get_section(MessageSection.ANSWER, ancount)
+ self._get_section(MessageSection.AUTHORITY, aucount)
+ self._get_section(MessageSection.ADDITIONAL, adcount)
+ if not self.ignore_trailing and self.parser.remaining() != 0:
+ raise TrailingJunk
+ if self.multi and self.message.tsig_ctx and not self.message.had_tsig:
+ self.message.tsig_ctx.update(self.parser.wire)
+ except Exception as e:
+ if self.continue_on_error:
+ self._add_error(e)
+ else:
+ raise
+ return self.message
+
+
+def from_wire(
+ wire: bytes,
+ keyring: Optional[Any] = None,
+ request_mac: Optional[bytes] = b"",
+ xfr: bool = False,
+ origin: Optional[dns.name.Name] = None,
+ tsig_ctx: Optional[Union[dns.tsig.HMACTSig, dns.tsig.GSSTSig]] = None,
+ multi: bool = False,
+ question_only: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ raise_on_truncation: bool = False,
+ continue_on_error: bool = False,
+) -> Message:
+ """Convert a DNS wire format message into a message object.
+
+ *keyring*, a ``dns.tsig.Key`` or ``dict``, the key or keyring to use if the message
+ is signed.
+
+ *request_mac*, a ``bytes`` or ``None``. If the message is a response to a
+ TSIG-signed request, *request_mac* should be set to the MAC of that request.
+
+ *xfr*, a ``bool``, should be set to ``True`` if this message is part of a zone
+ transfer.
+
+ *origin*, a ``dns.name.Name`` or ``None``. If the message is part of a zone
+ transfer, *origin* should be the origin name of the zone. If not ``None``, names
+ will be relativized to the origin.
+
+ *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the ongoing TSIG
+ context, used when validating zone transfers.
+
+ *multi*, a ``bool``, should be set to ``True`` if this message is part of a multiple
+ message sequence.
+
+ *question_only*, a ``bool``. If ``True``, read only up to the end of the question
+ section.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
+ message.
+
+ *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if the TC bit is
+ set.
+
+ *continue_on_error*, a ``bool``. If ``True``, try to continue parsing even if
+ errors occur. Erroneous rdata will be ignored. Errors will be accumulated as a
+ list of MessageError objects in the message's ``errors`` attribute. This option is
+ recommended only for DNS analysis tools, or for use in a server as part of an error
+ handling path. The default is ``False``.
+
+ Raises ``dns.message.ShortHeader`` if the message is less than 12 octets long.
+
+ Raises ``dns.message.TrailingJunk`` if there were octets in the message past the end
+ of the proper DNS message, and *ignore_trailing* is ``False``.
+
+ Raises ``dns.message.BadEDNS`` if an OPT record was in the wrong section, or
+ occurred more than once.
+
+ Raises ``dns.message.BadTSIG`` if a TSIG record was not the last record of the
+ additional data section.
+
+ Raises ``dns.message.Truncated`` if the TC flag is set and *raise_on_truncation* is
+ ``True``.
+
+ Returns a ``dns.message.Message``.
+ """
+
+ # We permit None for request_mac solely for backwards compatibility
+ if request_mac is None:
+ request_mac = b""
+
+ def initialize_message(message):
+ message.request_mac = request_mac
+ message.xfr = xfr
+ message.origin = origin
+ message.tsig_ctx = tsig_ctx
+
+ reader = _WireReader(
+ wire,
+ initialize_message,
+ question_only,
+ one_rr_per_rrset,
+ ignore_trailing,
+ keyring,
+ multi,
+ continue_on_error,
+ )
+ try:
+ m = reader.read()
+ except dns.exception.FormError:
+ if (
+ reader.message
+ and (reader.message.flags & dns.flags.TC)
+ and raise_on_truncation
+ ):
+ raise Truncated(message=reader.message)
+ else:
+ raise
+ # Reading a truncated message might not have any errors, so we
+ # have to do this check here too.
+ if m.flags & dns.flags.TC and raise_on_truncation:
+ raise Truncated(message=m)
+ if continue_on_error:
+ m.errors = reader.errors
+
+ return m
+
+
+class _TextReader:
+ """Text format reader.
+
+ tok: the tokenizer.
+ message: The message object being built.
+ DNS dynamic updates.
+ last_name: The most recently read name when building a message object.
+ one_rr_per_rrset: Put each RR into its own RRset?
+ origin: The origin for relative names
+ relativize: relativize names?
+ relativize_to: the origin to relativize to.
+ """
+
+ def __init__(
+ self,
+ text,
+ idna_codec,
+ one_rr_per_rrset=False,
+ origin=None,
+ relativize=True,
+ relativize_to=None,
+ ):
+ self.message = None
+ self.tok = dns.tokenizer.Tokenizer(text, idna_codec=idna_codec)
+ self.last_name = None
+ self.one_rr_per_rrset = one_rr_per_rrset
+ self.origin = origin
+ self.relativize = relativize
+ self.relativize_to = relativize_to
+ self.id = None
+ self.edns = -1
+ self.ednsflags = 0
+ self.payload = DEFAULT_EDNS_PAYLOAD
+ self.rcode = None
+ self.opcode = dns.opcode.QUERY
+ self.flags = 0
+
+ def _header_line(self, _):
+ """Process one line from the text format header section."""
+
+ token = self.tok.get()
+ what = token.value
+ if what == "id":
+ self.id = self.tok.get_int()
+ elif what == "flags":
+ while True:
+ token = self.tok.get()
+ if not token.is_identifier():
+ self.tok.unget(token)
+ break
+ self.flags = self.flags | dns.flags.from_text(token.value)
+ elif what == "edns":
+ self.edns = self.tok.get_int()
+ self.ednsflags = self.ednsflags | (self.edns << 16)
+ elif what == "eflags":
+ if self.edns < 0:
+ self.edns = 0
+ while True:
+ token = self.tok.get()
+ if not token.is_identifier():
+ self.tok.unget(token)
+ break
+ self.ednsflags = self.ednsflags | dns.flags.edns_from_text(token.value)
+ elif what == "payload":
+ self.payload = self.tok.get_int()
+ if self.edns < 0:
+ self.edns = 0
+ elif what == "opcode":
+ text = self.tok.get_string()
+ self.opcode = dns.opcode.from_text(text)
+ self.flags = self.flags | dns.opcode.to_flags(self.opcode)
+ elif what == "rcode":
+ text = self.tok.get_string()
+ self.rcode = dns.rcode.from_text(text)
+ else:
+ raise UnknownHeaderField
+ self.tok.get_eol()
+
+ def _question_line(self, section_number):
+ """Process one line from the text format question section."""
+
+ section = self.message.sections[section_number]
+ token = self.tok.get(want_leading=True)
+ if not token.is_whitespace():
+ self.last_name = self.tok.as_name(
+ token, self.message.origin, self.relativize, self.relativize_to
+ )
+ name = self.last_name
+ if name is None:
+ raise NoPreviousName
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ # Class
+ try:
+ rdclass = dns.rdataclass.from_text(token.value)
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except dns.exception.SyntaxError:
+ raise dns.exception.SyntaxError
+ except Exception:
+ rdclass = dns.rdataclass.IN
+ # Type
+ rdtype = dns.rdatatype.from_text(token.value)
+ (rdclass, rdtype, _, _) = self.message._parse_rr_header(
+ section_number, name, rdclass, rdtype
+ )
+ self.message.find_rrset(
+ section, name, rdclass, rdtype, create=True, force_unique=True
+ )
+ self.tok.get_eol()
+
+ def _rr_line(self, section_number):
+ """Process one line from the text format answer, authority, or
+ additional data sections.
+ """
+
+ section = self.message.sections[section_number]
+ # Name
+ token = self.tok.get(want_leading=True)
+ if not token.is_whitespace():
+ self.last_name = self.tok.as_name(
+ token, self.message.origin, self.relativize, self.relativize_to
+ )
+ name = self.last_name
+ if name is None:
+ raise NoPreviousName
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ # TTL
+ try:
+ ttl = int(token.value, 0)
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except dns.exception.SyntaxError:
+ raise dns.exception.SyntaxError
+ except Exception:
+ ttl = 0
+ # Class
+ try:
+ rdclass = dns.rdataclass.from_text(token.value)
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except dns.exception.SyntaxError:
+ raise dns.exception.SyntaxError
+ except Exception:
+ rdclass = dns.rdataclass.IN
+ # Type
+ rdtype = dns.rdatatype.from_text(token.value)
+ (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header(
+ section_number, name, rdclass, rdtype
+ )
+ token = self.tok.get()
+ if empty and not token.is_eol_or_eof():
+ raise dns.exception.SyntaxError
+ if not empty and token.is_eol_or_eof():
+ raise dns.exception.UnexpectedEnd
+ if not token.is_eol_or_eof():
+ self.tok.unget(token)
+ rd = dns.rdata.from_text(
+ rdclass,
+ rdtype,
+ self.tok,
+ self.message.origin,
+ self.relativize,
+ self.relativize_to,
+ )
+ covers = rd.covers()
+ else:
+ rd = None
+ covers = dns.rdatatype.NONE
+ rrset = self.message.find_rrset(
+ section,
+ name,
+ rdclass,
+ rdtype,
+ covers,
+ deleting,
+ True,
+ self.one_rr_per_rrset,
+ )
+ if rd is not None:
+ rrset.add(rd, ttl)
+
+ def _make_message(self):
+ factory = _message_factory_from_opcode(self.opcode)
+ message = factory(id=self.id)
+ message.flags = self.flags
+ if self.edns >= 0:
+ message.use_edns(self.edns, self.ednsflags, self.payload)
+ if self.rcode:
+ message.set_rcode(self.rcode)
+ if self.origin:
+ message.origin = self.origin
+ return message
+
+ def read(self):
+ """Read a text format DNS message and build a dns.message.Message
+ object."""
+
+ line_method = self._header_line
+ section_number = None
+ while 1:
+ token = self.tok.get(True, True)
+ if token.is_eol_or_eof():
+ break
+ if token.is_comment():
+ u = token.value.upper()
+ if u == "HEADER":
+ line_method = self._header_line
+
+ if self.message:
+ message = self.message
+ else:
+ # If we don't have a message, create one with the current
+ # opcode, so that we know which section names to parse.
+ message = self._make_message()
+ try:
+ section_number = message._section_enum.from_text(u)
+ # We found a section name. If we don't have a message,
+ # use the one we just created.
+ if not self.message:
+ self.message = message
+ self.one_rr_per_rrset = message._get_one_rr_per_rrset(
+ self.one_rr_per_rrset
+ )
+ if section_number == MessageSection.QUESTION:
+ line_method = self._question_line
+ else:
+ line_method = self._rr_line
+ except Exception:
+ # It's just a comment.
+ pass
+ self.tok.get_eol()
+ continue
+ self.tok.unget(token)
+ line_method(section_number)
+ if not self.message:
+ self.message = self._make_message()
+ return self.message
+
+
+def from_text(
+ text: str,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ one_rr_per_rrset: bool = False,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ relativize_to: Optional[dns.name.Name] = None,
+) -> Message:
+ """Convert the text format message into a message object.
+
+ The reader stops after reading the first blank line in the input to
+ facilitate reading multiple messages from a single file with
+ ``dns.message.from_file()``.
+
+ *text*, a ``str``, the text format message.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put
+ into its own rrset. The default is ``False``.
+
+ *origin*, a ``dns.name.Name`` (or ``None``), the
+ origin to use for relative names.
+
+ *relativize*, a ``bool``. If true, name will be relativized.
+
+ *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
+ when relativizing names. If not set, the *origin* value will be used.
+
+ Raises ``dns.message.UnknownHeaderField`` if a header is unknown.
+
+ Raises ``dns.exception.SyntaxError`` if the text is badly formed.
+
+ Returns a ``dns.message.Message object``
+ """
+
+ # 'text' can also be a file, but we don't publish that fact
+ # since it's an implementation detail. The official file
+ # interface is from_file().
+
+ reader = _TextReader(
+ text, idna_codec, one_rr_per_rrset, origin, relativize, relativize_to
+ )
+ return reader.read()
+
+
+def from_file(
+ f: Any,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ one_rr_per_rrset: bool = False,
+) -> Message:
+ """Read the next text format message from the specified file.
+
+ Message blocks are separated by a single blank line.
+
+ *f*, a ``file`` or ``str``. If *f* is text, it is treated as the
+ pathname of a file to open.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put
+ into its own rrset. The default is ``False``.
+
+ Raises ``dns.message.UnknownHeaderField`` if a header is unknown.
+
+ Raises ``dns.exception.SyntaxError`` if the text is badly formed.
+
+ Returns a ``dns.message.Message object``
+ """
+
+ if isinstance(f, str):
+ cm: contextlib.AbstractContextManager = open(f)
+ else:
+ cm = contextlib.nullcontext(f)
+ with cm as f:
+ return from_text(f, idna_codec, one_rr_per_rrset)
+ assert False # for mypy lgtm[py/unreachable-statement]
+
+
+def make_query(
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ use_edns: Optional[Union[int, bool]] = None,
+ want_dnssec: bool = False,
+ ednsflags: Optional[int] = None,
+ payload: Optional[int] = None,
+ request_payload: Optional[int] = None,
+ options: Optional[List[dns.edns.Option]] = None,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ id: Optional[int] = None,
+ flags: int = dns.flags.RD,
+ pad: int = 0,
+) -> QueryMessage:
+ """Make a query message.
+
+ The query name, type, and class may all be specified either
+ as objects of the appropriate type, or as strings.
+
+ The query will have a randomly chosen query id, and its DNS flags
+ will be set to dns.flags.RD.
+
+ qname, a ``dns.name.Name`` or ``str``, the query name.
+
+ *rdtype*, an ``int`` or ``str``, the desired rdata type.
+
+ *rdclass*, an ``int`` or ``str``, the desired rdata class; the default
+ is class IN.
+
+ *use_edns*, an ``int``, ``bool`` or ``None``. The EDNS level to use; the
+ default is ``None``. If ``None``, EDNS will be enabled only if other
+ parameters (*ednsflags*, *payload*, *request_payload*, or *options*) are
+ set.
+ See the description of dns.message.Message.use_edns() for the possible
+ values for use_edns and their meanings.
+
+ *want_dnssec*, a ``bool``. If ``True``, DNSSEC data is desired.
+
+ *ednsflags*, an ``int``, the EDNS flag values.
+
+ *payload*, an ``int``, is the EDNS sender's payload field, which is the
+ maximum size of UDP datagram the sender can handle. I.e. how big
+ a response to this message can be.
+
+ *request_payload*, an ``int``, is the EDNS payload size to use when
+ sending this message. If not specified, defaults to the value of
+ *payload*.
+
+ *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS
+ options.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ *id*, an ``int`` or ``None``, the desired query id. The default is
+ ``None``, which generates a random query id.
+
+ *flags*, an ``int``, the desired query flags. The default is
+ ``dns.flags.RD``.
+
+ *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add
+ padding bytes to make the message size a multiple of *pad*. Note that if
+ padding is non-zero, an EDNS PADDING option will always be added to the
+ message.
+
+ Returns a ``dns.message.QueryMessage``
+ """
+
+ if isinstance(qname, str):
+ qname = dns.name.from_text(qname, idna_codec=idna_codec)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ m = QueryMessage(id=id)
+ m.flags = dns.flags.Flag(flags)
+ m.find_rrset(m.question, qname, rdclass, rdtype, create=True, force_unique=True)
+ # only pass keywords on to use_edns if they have been set to a
+ # non-None value. Setting a field will turn EDNS on if it hasn't
+ # been configured.
+ kwargs: Dict[str, Any] = {}
+ if ednsflags is not None:
+ kwargs["ednsflags"] = ednsflags
+ if payload is not None:
+ kwargs["payload"] = payload
+ if request_payload is not None:
+ kwargs["request_payload"] = request_payload
+ if options is not None:
+ kwargs["options"] = options
+ if kwargs and use_edns is None:
+ use_edns = 0
+ kwargs["edns"] = use_edns
+ kwargs["pad"] = pad
+ m.use_edns(**kwargs)
+ m.want_dnssec(want_dnssec)
+ return m
+
+
+def make_response(
+ query: Message,
+ recursion_available: bool = False,
+ our_payload: int = 8192,
+ fudge: int = 300,
+ tsig_error: int = 0,
+ pad: Optional[int] = None,
+) -> Message:
+ """Make a message which is a response for the specified query.
+ The message returned is really a response skeleton; it has all of the infrastructure
+ required of a response, but none of the content.
+
+ The response's question section is a shallow copy of the query's question section,
+ so the query's question RRsets should not be changed.
+
+ *query*, a ``dns.message.Message``, the query to respond to.
+
+ *recursion_available*, a ``bool``, should RA be set in the response?
+
+ *our_payload*, an ``int``, the payload size to advertise in EDNS responses.
+
+ *fudge*, an ``int``, the TSIG time fudge.
+
+ *tsig_error*, an ``int``, the TSIG error.
+
+ *pad*, a non-negative ``int`` or ``None``. If 0, the default, do not pad; otherwise
+ if not ``None`` add padding bytes to make the message size a multiple of *pad*.
+ Note that if padding is non-zero, an EDNS PADDING option will always be added to the
+ message. If ``None``, add padding following RFC 8467, namely if the request is
+ padded, pad the response to 468 otherwise do not pad.
+
+ Returns a ``dns.message.Message`` object whose specific class is appropriate for the
+ query. For example, if query is a ``dns.update.UpdateMessage``, response will be
+ too.
+ """
+
+ if query.flags & dns.flags.QR:
+ raise dns.exception.FormError("specified query message is not a query")
+ factory = _message_factory_from_opcode(query.opcode())
+ response = factory(id=query.id)
+ response.flags = dns.flags.QR | (query.flags & dns.flags.RD)
+ if recursion_available:
+ response.flags |= dns.flags.RA
+ response.set_opcode(query.opcode())
+ response.question = list(query.question)
+ if query.edns >= 0:
+ if pad is None:
+ # Set response padding per RFC 8467
+ pad = 0
+ for option in query.options:
+ if option.otype == dns.edns.OptionType.PADDING:
+ pad = 468
+ response.use_edns(0, 0, our_payload, query.payload, pad=pad)
+ if query.had_tsig:
+ response.use_tsig(
+ query.keyring,
+ query.keyname,
+ fudge,
+ None,
+ tsig_error,
+ b"",
+ query.keyalgorithm,
+ )
+ response.request_mac = query.mac
+ return response
+
+
+### BEGIN generated MessageSection constants
+
+QUESTION = MessageSection.QUESTION
+ANSWER = MessageSection.ANSWER
+AUTHORITY = MessageSection.AUTHORITY
+ADDITIONAL = MessageSection.ADDITIONAL
+
+### END generated MessageSection constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/name.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/name.py
new file mode 100644
index 0000000000000000000000000000000000000000..22ccb39211e113e68a3c4121d0a68181d6d9c9f8
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/name.py
@@ -0,0 +1,1283 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Names.
+"""
+
+import copy
+import encodings.idna # type: ignore
+import functools
+import struct
+from typing import Any, Callable, Dict, Iterable, Optional, Tuple, Union
+
+import dns._features
+import dns.enum
+import dns.exception
+import dns.immutable
+import dns.wire
+
+if dns._features.have("idna"):
+ import idna # type: ignore
+
+ have_idna_2008 = True
+else: # pragma: no cover
+ have_idna_2008 = False
+
+CompressType = Dict["Name", int]
+
+
+class NameRelation(dns.enum.IntEnum):
+ """Name relation result from fullcompare()."""
+
+ # This is an IntEnum for backwards compatibility in case anyone
+ # has hardwired the constants.
+
+ #: The compared names have no relationship to each other.
+ NONE = 0
+ #: the first name is a superdomain of the second.
+ SUPERDOMAIN = 1
+ #: The first name is a subdomain of the second.
+ SUBDOMAIN = 2
+ #: The compared names are equal.
+ EQUAL = 3
+ #: The compared names have a common ancestor.
+ COMMONANCESTOR = 4
+
+ @classmethod
+ def _maximum(cls):
+ return cls.COMMONANCESTOR
+
+ @classmethod
+ def _short_name(cls):
+ return cls.__name__
+
+
+# Backwards compatibility
+NAMERELN_NONE = NameRelation.NONE
+NAMERELN_SUPERDOMAIN = NameRelation.SUPERDOMAIN
+NAMERELN_SUBDOMAIN = NameRelation.SUBDOMAIN
+NAMERELN_EQUAL = NameRelation.EQUAL
+NAMERELN_COMMONANCESTOR = NameRelation.COMMONANCESTOR
+
+
+class EmptyLabel(dns.exception.SyntaxError):
+ """A DNS label is empty."""
+
+
+class BadEscape(dns.exception.SyntaxError):
+ """An escaped code in a text format of DNS name is invalid."""
+
+
+class BadPointer(dns.exception.FormError):
+ """A DNS compression pointer points forward instead of backward."""
+
+
+class BadLabelType(dns.exception.FormError):
+ """The label type in DNS name wire format is unknown."""
+
+
+class NeedAbsoluteNameOrOrigin(dns.exception.DNSException):
+ """An attempt was made to convert a non-absolute name to
+ wire when there was also a non-absolute (or missing) origin."""
+
+
+class NameTooLong(dns.exception.FormError):
+ """A DNS name is > 255 octets long."""
+
+
+class LabelTooLong(dns.exception.SyntaxError):
+ """A DNS label is > 63 octets long."""
+
+
+class AbsoluteConcatenation(dns.exception.DNSException):
+ """An attempt was made to append anything other than the
+ empty name to an absolute DNS name."""
+
+
+class NoParent(dns.exception.DNSException):
+ """An attempt was made to get the parent of the root name
+ or the empty name."""
+
+
+class NoIDNA2008(dns.exception.DNSException):
+ """IDNA 2008 processing was requested but the idna module is not
+ available."""
+
+
+class IDNAException(dns.exception.DNSException):
+ """IDNA processing raised an exception."""
+
+ supp_kwargs = {"idna_exception"}
+ fmt = "IDNA processing exception: {idna_exception}"
+
+ # We do this as otherwise mypy complains about unexpected keyword argument
+ # idna_exception
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+
+class NeedSubdomainOfOrigin(dns.exception.DNSException):
+ """An absolute name was provided that is not a subdomain of the specified origin."""
+
+
+_escaped = b'"().;\\@$'
+_escaped_text = '"().;\\@$'
+
+
+def _escapify(label: Union[bytes, str]) -> str:
+ """Escape the characters in label which need it.
+ @returns: the escaped string
+ @rtype: string"""
+ if isinstance(label, bytes):
+ # Ordinary DNS label mode. Escape special characters and values
+ # < 0x20 or > 0x7f.
+ text = ""
+ for c in label:
+ if c in _escaped:
+ text += "\\" + chr(c)
+ elif c > 0x20 and c < 0x7F:
+ text += chr(c)
+ else:
+ text += "\\%03d" % c
+ return text
+
+ # Unicode label mode. Escape only special characters and values < 0x20
+ text = ""
+ for uc in label:
+ if uc in _escaped_text:
+ text += "\\" + uc
+ elif uc <= "\x20":
+ text += "\\%03d" % ord(uc)
+ else:
+ text += uc
+ return text
+
+
+class IDNACodec:
+ """Abstract base class for IDNA encoder/decoders."""
+
+ def __init__(self):
+ pass
+
+ def is_idna(self, label: bytes) -> bool:
+ return label.lower().startswith(b"xn--")
+
+ def encode(self, label: str) -> bytes:
+ raise NotImplementedError # pragma: no cover
+
+ def decode(self, label: bytes) -> str:
+ # We do not apply any IDNA policy on decode.
+ if self.is_idna(label):
+ try:
+ slabel = label[4:].decode("punycode")
+ return _escapify(slabel)
+ except Exception as e:
+ raise IDNAException(idna_exception=e)
+ else:
+ return _escapify(label)
+
+
+class IDNA2003Codec(IDNACodec):
+ """IDNA 2003 encoder/decoder."""
+
+ def __init__(self, strict_decode: bool = False):
+ """Initialize the IDNA 2003 encoder/decoder.
+
+ *strict_decode* is a ``bool``. If `True`, then IDNA2003 checking
+ is done when decoding. This can cause failures if the name
+ was encoded with IDNA2008. The default is `False`.
+ """
+
+ super().__init__()
+ self.strict_decode = strict_decode
+
+ def encode(self, label: str) -> bytes:
+ """Encode *label*."""
+
+ if label == "":
+ return b""
+ try:
+ return encodings.idna.ToASCII(label)
+ except UnicodeError:
+ raise LabelTooLong
+
+ def decode(self, label: bytes) -> str:
+ """Decode *label*."""
+ if not self.strict_decode:
+ return super().decode(label)
+ if label == b"":
+ return ""
+ try:
+ return _escapify(encodings.idna.ToUnicode(label))
+ except Exception as e:
+ raise IDNAException(idna_exception=e)
+
+
+class IDNA2008Codec(IDNACodec):
+ """IDNA 2008 encoder/decoder."""
+
+ def __init__(
+ self,
+ uts_46: bool = False,
+ transitional: bool = False,
+ allow_pure_ascii: bool = False,
+ strict_decode: bool = False,
+ ):
+ """Initialize the IDNA 2008 encoder/decoder.
+
+ *uts_46* is a ``bool``. If True, apply Unicode IDNA
+ compatibility processing as described in Unicode Technical
+ Standard #46 (https://unicode.org/reports/tr46/).
+ If False, do not apply the mapping. The default is False.
+
+ *transitional* is a ``bool``: If True, use the
+ "transitional" mode described in Unicode Technical Standard
+ #46. The default is False.
+
+ *allow_pure_ascii* is a ``bool``. If True, then a label which
+ consists of only ASCII characters is allowed. This is less
+ strict than regular IDNA 2008, but is also necessary for mixed
+ names, e.g. a name with starting with "_sip._tcp." and ending
+ in an IDN suffix which would otherwise be disallowed. The
+ default is False.
+
+ *strict_decode* is a ``bool``: If True, then IDNA2008 checking
+ is done when decoding. This can cause failures if the name
+ was encoded with IDNA2003. The default is False.
+ """
+ super().__init__()
+ self.uts_46 = uts_46
+ self.transitional = transitional
+ self.allow_pure_ascii = allow_pure_ascii
+ self.strict_decode = strict_decode
+
+ def encode(self, label: str) -> bytes:
+ if label == "":
+ return b""
+ if self.allow_pure_ascii and is_all_ascii(label):
+ encoded = label.encode("ascii")
+ if len(encoded) > 63:
+ raise LabelTooLong
+ return encoded
+ if not have_idna_2008:
+ raise NoIDNA2008
+ try:
+ if self.uts_46:
+ label = idna.uts46_remap(label, False, self.transitional)
+ return idna.alabel(label)
+ except idna.IDNAError as e:
+ if e.args[0] == "Label too long":
+ raise LabelTooLong
+ else:
+ raise IDNAException(idna_exception=e)
+
+ def decode(self, label: bytes) -> str:
+ if not self.strict_decode:
+ return super().decode(label)
+ if label == b"":
+ return ""
+ if not have_idna_2008:
+ raise NoIDNA2008
+ try:
+ ulabel = idna.ulabel(label)
+ if self.uts_46:
+ ulabel = idna.uts46_remap(ulabel, False, self.transitional)
+ return _escapify(ulabel)
+ except (idna.IDNAError, UnicodeError) as e:
+ raise IDNAException(idna_exception=e)
+
+
+IDNA_2003_Practical = IDNA2003Codec(False)
+IDNA_2003_Strict = IDNA2003Codec(True)
+IDNA_2003 = IDNA_2003_Practical
+IDNA_2008_Practical = IDNA2008Codec(True, False, True, False)
+IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False)
+IDNA_2008_Strict = IDNA2008Codec(False, False, False, True)
+IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False)
+IDNA_2008 = IDNA_2008_Practical
+
+
+def _validate_labels(labels: Tuple[bytes, ...]) -> None:
+ """Check for empty labels in the middle of a label sequence,
+ labels that are too long, and for too many labels.
+
+ Raises ``dns.name.NameTooLong`` if the name as a whole is too long.
+
+ Raises ``dns.name.EmptyLabel`` if a label is empty (i.e. the root
+ label) and appears in a position other than the end of the label
+ sequence
+
+ """
+
+ l = len(labels)
+ total = 0
+ i = -1
+ j = 0
+ for label in labels:
+ ll = len(label)
+ total += ll + 1
+ if ll > 63:
+ raise LabelTooLong
+ if i < 0 and label == b"":
+ i = j
+ j += 1
+ if total > 255:
+ raise NameTooLong
+ if i >= 0 and i != l - 1:
+ raise EmptyLabel
+
+
+def _maybe_convert_to_binary(label: Union[bytes, str]) -> bytes:
+ """If label is ``str``, convert it to ``bytes``. If it is already
+ ``bytes`` just return it.
+
+ """
+
+ if isinstance(label, bytes):
+ return label
+ if isinstance(label, str):
+ return label.encode()
+ raise ValueError # pragma: no cover
+
+
+@dns.immutable.immutable
+class Name:
+ """A DNS name.
+
+ The dns.name.Name class represents a DNS name as a tuple of
+ labels. Each label is a ``bytes`` in DNS wire format. Instances
+ of the class are immutable.
+ """
+
+ __slots__ = ["labels"]
+
+ def __init__(self, labels: Iterable[Union[bytes, str]]):
+ """*labels* is any iterable whose values are ``str`` or ``bytes``."""
+
+ blabels = [_maybe_convert_to_binary(x) for x in labels]
+ self.labels = tuple(blabels)
+ _validate_labels(self.labels)
+
+ def __copy__(self):
+ return Name(self.labels)
+
+ def __deepcopy__(self, memo):
+ return Name(copy.deepcopy(self.labels, memo))
+
+ def __getstate__(self):
+ # Names can be pickled
+ return {"labels": self.labels}
+
+ def __setstate__(self, state):
+ super().__setattr__("labels", state["labels"])
+ _validate_labels(self.labels)
+
+ def is_absolute(self) -> bool:
+ """Is the most significant label of this name the root label?
+
+ Returns a ``bool``.
+ """
+
+ return len(self.labels) > 0 and self.labels[-1] == b""
+
+ def is_wild(self) -> bool:
+ """Is this name wild? (I.e. Is the least significant label '*'?)
+
+ Returns a ``bool``.
+ """
+
+ return len(self.labels) > 0 and self.labels[0] == b"*"
+
+ def __hash__(self) -> int:
+ """Return a case-insensitive hash of the name.
+
+ Returns an ``int``.
+ """
+
+ h = 0
+ for label in self.labels:
+ for c in label.lower():
+ h += (h << 3) + c
+ return h
+
+ def fullcompare(self, other: "Name") -> Tuple[NameRelation, int, int]:
+ """Compare two names, returning a 3-tuple
+ ``(relation, order, nlabels)``.
+
+ *relation* describes the relation ship between the names,
+ and is one of: ``dns.name.NameRelation.NONE``,
+ ``dns.name.NameRelation.SUPERDOMAIN``, ``dns.name.NameRelation.SUBDOMAIN``,
+ ``dns.name.NameRelation.EQUAL``, or ``dns.name.NameRelation.COMMONANCESTOR``.
+
+ *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and ==
+ 0 if *self* == *other*. A relative name is always less than an
+ absolute name. If both names have the same relativity, then
+ the DNSSEC order relation is used to order them.
+
+ *nlabels* is the number of significant labels that the two names
+ have in common.
+
+ Here are some examples. Names ending in "." are absolute names,
+ those not ending in "." are relative names.
+
+ ============= ============= =========== ===== =======
+ self other relation order nlabels
+ ============= ============= =========== ===== =======
+ www.example. www.example. equal 0 3
+ www.example. example. subdomain > 0 2
+ example. www.example. superdomain < 0 2
+ example1.com. example2.com. common anc. < 0 2
+ example1 example2. none < 0 0
+ example1. example2 none > 0 0
+ ============= ============= =========== ===== =======
+ """
+
+ sabs = self.is_absolute()
+ oabs = other.is_absolute()
+ if sabs != oabs:
+ if sabs:
+ return (NameRelation.NONE, 1, 0)
+ else:
+ return (NameRelation.NONE, -1, 0)
+ l1 = len(self.labels)
+ l2 = len(other.labels)
+ ldiff = l1 - l2
+ if ldiff < 0:
+ l = l1
+ else:
+ l = l2
+
+ order = 0
+ nlabels = 0
+ namereln = NameRelation.NONE
+ while l > 0:
+ l -= 1
+ l1 -= 1
+ l2 -= 1
+ label1 = self.labels[l1].lower()
+ label2 = other.labels[l2].lower()
+ if label1 < label2:
+ order = -1
+ if nlabels > 0:
+ namereln = NameRelation.COMMONANCESTOR
+ return (namereln, order, nlabels)
+ elif label1 > label2:
+ order = 1
+ if nlabels > 0:
+ namereln = NameRelation.COMMONANCESTOR
+ return (namereln, order, nlabels)
+ nlabels += 1
+ order = ldiff
+ if ldiff < 0:
+ namereln = NameRelation.SUPERDOMAIN
+ elif ldiff > 0:
+ namereln = NameRelation.SUBDOMAIN
+ else:
+ namereln = NameRelation.EQUAL
+ return (namereln, order, nlabels)
+
+ def is_subdomain(self, other: "Name") -> bool:
+ """Is self a subdomain of other?
+
+ Note that the notion of subdomain includes equality, e.g.
+ "dnspython.org" is a subdomain of itself.
+
+ Returns a ``bool``.
+ """
+
+ (nr, _, _) = self.fullcompare(other)
+ if nr == NameRelation.SUBDOMAIN or nr == NameRelation.EQUAL:
+ return True
+ return False
+
+ def is_superdomain(self, other: "Name") -> bool:
+ """Is self a superdomain of other?
+
+ Note that the notion of superdomain includes equality, e.g.
+ "dnspython.org" is a superdomain of itself.
+
+ Returns a ``bool``.
+ """
+
+ (nr, _, _) = self.fullcompare(other)
+ if nr == NameRelation.SUPERDOMAIN or nr == NameRelation.EQUAL:
+ return True
+ return False
+
+ def canonicalize(self) -> "Name":
+ """Return a name which is equal to the current name, but is in
+ DNSSEC canonical form.
+ """
+
+ return Name([x.lower() for x in self.labels])
+
+ def __eq__(self, other):
+ if isinstance(other, Name):
+ return self.fullcompare(other)[1] == 0
+ else:
+ return False
+
+ def __ne__(self, other):
+ if isinstance(other, Name):
+ return self.fullcompare(other)[1] != 0
+ else:
+ return True
+
+ def __lt__(self, other):
+ if isinstance(other, Name):
+ return self.fullcompare(other)[1] < 0
+ else:
+ return NotImplemented
+
+ def __le__(self, other):
+ if isinstance(other, Name):
+ return self.fullcompare(other)[1] <= 0
+ else:
+ return NotImplemented
+
+ def __ge__(self, other):
+ if isinstance(other, Name):
+ return self.fullcompare(other)[1] >= 0
+ else:
+ return NotImplemented
+
+ def __gt__(self, other):
+ if isinstance(other, Name):
+ return self.fullcompare(other)[1] > 0
+ else:
+ return NotImplemented
+
+ def __repr__(self):
+ return ""
+
+ def __str__(self):
+ return self.to_text(False)
+
+ def to_text(self, omit_final_dot: bool = False) -> str:
+ """Convert name to DNS text format.
+
+ *omit_final_dot* is a ``bool``. If True, don't emit the final
+ dot (denoting the root label) for absolute names. The default
+ is False.
+
+ Returns a ``str``.
+ """
+
+ if len(self.labels) == 0:
+ return "@"
+ if len(self.labels) == 1 and self.labels[0] == b"":
+ return "."
+ if omit_final_dot and self.is_absolute():
+ l = self.labels[:-1]
+ else:
+ l = self.labels
+ s = ".".join(map(_escapify, l))
+ return s
+
+ def to_unicode(
+ self, omit_final_dot: bool = False, idna_codec: Optional[IDNACodec] = None
+ ) -> str:
+ """Convert name to Unicode text format.
+
+ IDN ACE labels are converted to Unicode.
+
+ *omit_final_dot* is a ``bool``. If True, don't emit the final
+ dot (denoting the root label) for absolute names. The default
+ is False.
+ *idna_codec* specifies the IDNA encoder/decoder. If None, the
+ dns.name.IDNA_2003_Practical encoder/decoder is used.
+ The IDNA_2003_Practical decoder does
+ not impose any policy, it just decodes punycode, so if you
+ don't want checking for compliance, you can use this decoder
+ for IDNA2008 as well.
+
+ Returns a ``str``.
+ """
+
+ if len(self.labels) == 0:
+ return "@"
+ if len(self.labels) == 1 and self.labels[0] == b"":
+ return "."
+ if omit_final_dot and self.is_absolute():
+ l = self.labels[:-1]
+ else:
+ l = self.labels
+ if idna_codec is None:
+ idna_codec = IDNA_2003_Practical
+ return ".".join([idna_codec.decode(x) for x in l])
+
+ def to_digestable(self, origin: Optional["Name"] = None) -> bytes:
+ """Convert name to a format suitable for digesting in hashes.
+
+ The name is canonicalized and converted to uncompressed wire
+ format. All names in wire format are absolute. If the name
+ is a relative name, then an origin must be supplied.
+
+ *origin* is a ``dns.name.Name`` or ``None``. If the name is
+ relative and origin is not ``None``, then origin will be appended
+ to the name.
+
+ Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is
+ relative and no origin was provided.
+
+ Returns a ``bytes``.
+ """
+
+ digest = self.to_wire(origin=origin, canonicalize=True)
+ assert digest is not None
+ return digest
+
+ def to_wire(
+ self,
+ file: Optional[Any] = None,
+ compress: Optional[CompressType] = None,
+ origin: Optional["Name"] = None,
+ canonicalize: bool = False,
+ ) -> Optional[bytes]:
+ """Convert name to wire format, possibly compressing it.
+
+ *file* is the file where the name is emitted (typically an
+ io.BytesIO file). If ``None`` (the default), a ``bytes``
+ containing the wire name will be returned.
+
+ *compress*, a ``dict``, is the compression table to use. If
+ ``None`` (the default), names will not be compressed. Note that
+ the compression code assumes that compression offset 0 is the
+ start of *file*, and thus compression will not be correct
+ if this is not the case.
+
+ *origin* is a ``dns.name.Name`` or ``None``. If the name is
+ relative and origin is not ``None``, then *origin* will be appended
+ to it.
+
+ *canonicalize*, a ``bool``, indicates whether the name should
+ be canonicalized; that is, converted to a format suitable for
+ digesting in hashes.
+
+ Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is
+ relative and no origin was provided.
+
+ Returns a ``bytes`` or ``None``.
+ """
+
+ if file is None:
+ out = bytearray()
+ for label in self.labels:
+ out.append(len(label))
+ if canonicalize:
+ out += label.lower()
+ else:
+ out += label
+ if not self.is_absolute():
+ if origin is None or not origin.is_absolute():
+ raise NeedAbsoluteNameOrOrigin
+ for label in origin.labels:
+ out.append(len(label))
+ if canonicalize:
+ out += label.lower()
+ else:
+ out += label
+ return bytes(out)
+
+ labels: Iterable[bytes]
+ if not self.is_absolute():
+ if origin is None or not origin.is_absolute():
+ raise NeedAbsoluteNameOrOrigin
+ labels = list(self.labels)
+ labels.extend(list(origin.labels))
+ else:
+ labels = self.labels
+ i = 0
+ for label in labels:
+ n = Name(labels[i:])
+ i += 1
+ if compress is not None:
+ pos = compress.get(n)
+ else:
+ pos = None
+ if pos is not None:
+ value = 0xC000 + pos
+ s = struct.pack("!H", value)
+ file.write(s)
+ break
+ else:
+ if compress is not None and len(n) > 1:
+ pos = file.tell()
+ if pos <= 0x3FFF:
+ compress[n] = pos
+ l = len(label)
+ file.write(struct.pack("!B", l))
+ if l > 0:
+ if canonicalize:
+ file.write(label.lower())
+ else:
+ file.write(label)
+ return None
+
+ def __len__(self) -> int:
+ """The length of the name (in labels).
+
+ Returns an ``int``.
+ """
+
+ return len(self.labels)
+
+ def __getitem__(self, index):
+ return self.labels[index]
+
+ def __add__(self, other):
+ return self.concatenate(other)
+
+ def __sub__(self, other):
+ return self.relativize(other)
+
+ def split(self, depth: int) -> Tuple["Name", "Name"]:
+ """Split a name into a prefix and suffix names at the specified depth.
+
+ *depth* is an ``int`` specifying the number of labels in the suffix
+
+ Raises ``ValueError`` if *depth* was not >= 0 and <= the length of the
+ name.
+
+ Returns the tuple ``(prefix, suffix)``.
+ """
+
+ l = len(self.labels)
+ if depth == 0:
+ return (self, dns.name.empty)
+ elif depth == l:
+ return (dns.name.empty, self)
+ elif depth < 0 or depth > l:
+ raise ValueError("depth must be >= 0 and <= the length of the name")
+ return (Name(self[:-depth]), Name(self[-depth:]))
+
+ def concatenate(self, other: "Name") -> "Name":
+ """Return a new name which is the concatenation of self and other.
+
+ Raises ``dns.name.AbsoluteConcatenation`` if the name is
+ absolute and *other* is not the empty name.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if self.is_absolute() and len(other) > 0:
+ raise AbsoluteConcatenation
+ labels = list(self.labels)
+ labels.extend(list(other.labels))
+ return Name(labels)
+
+ def relativize(self, origin: "Name") -> "Name":
+ """If the name is a subdomain of *origin*, return a new name which is
+ the name relative to origin. Otherwise return the name.
+
+ For example, relativizing ``www.dnspython.org.`` to origin
+ ``dnspython.org.`` returns the name ``www``. Relativizing ``example.``
+ to origin ``dnspython.org.`` returns ``example.``.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if origin is not None and self.is_subdomain(origin):
+ return Name(self[: -len(origin)])
+ else:
+ return self
+
+ def derelativize(self, origin: "Name") -> "Name":
+ """If the name is a relative name, return a new name which is the
+ concatenation of the name and origin. Otherwise return the name.
+
+ For example, derelativizing ``www`` to origin ``dnspython.org.``
+ returns the name ``www.dnspython.org.``. Derelativizing ``example.``
+ to origin ``dnspython.org.`` returns ``example.``.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if not self.is_absolute():
+ return self.concatenate(origin)
+ else:
+ return self
+
+ def choose_relativity(
+ self, origin: Optional["Name"] = None, relativize: bool = True
+ ) -> "Name":
+ """Return a name with the relativity desired by the caller.
+
+ If *origin* is ``None``, then the name is returned.
+ Otherwise, if *relativize* is ``True`` the name is
+ relativized, and if *relativize* is ``False`` the name is
+ derelativized.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if origin:
+ if relativize:
+ return self.relativize(origin)
+ else:
+ return self.derelativize(origin)
+ else:
+ return self
+
+ def parent(self) -> "Name":
+ """Return the parent of the name.
+
+ For example, the parent of ``www.dnspython.org.`` is ``dnspython.org``.
+
+ Raises ``dns.name.NoParent`` if the name is either the root name or the
+ empty name, and thus has no parent.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if self == root or self == empty:
+ raise NoParent
+ return Name(self.labels[1:])
+
+ def predecessor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
+ """Return the maximal predecessor of *name* in the DNSSEC ordering in the zone
+ whose origin is *origin*, or return the longest name under *origin* if the
+ name is origin (i.e. wrap around to the longest name, which may still be
+ *origin* due to length considerations.
+
+ The relativity of the name is preserved, so if this name is relative
+ then the method will return a relative name, and likewise if this name
+ is absolute then the predecessor will be absolute.
+
+ *prefix_ok* indicates if prefixing labels is allowed, and
+ defaults to ``True``. Normally it is good to allow this, but if computing
+ a maximal predecessor at a zone cut point then ``False`` must be specified.
+ """
+ return _handle_relativity_and_call(
+ _absolute_predecessor, self, origin, prefix_ok
+ )
+
+ def successor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
+ """Return the minimal successor of *name* in the DNSSEC ordering in the zone
+ whose origin is *origin*, or return *origin* if the successor cannot be
+ computed due to name length limitations.
+
+ Note that *origin* is returned in the "too long" cases because wrapping
+ around to the origin is how NSEC records express "end of the zone".
+
+ The relativity of the name is preserved, so if this name is relative
+ then the method will return a relative name, and likewise if this name
+ is absolute then the successor will be absolute.
+
+ *prefix_ok* indicates if prefixing a new minimal label is allowed, and
+ defaults to ``True``. Normally it is good to allow this, but if computing
+ a minimal successor at a zone cut point then ``False`` must be specified.
+ """
+ return _handle_relativity_and_call(_absolute_successor, self, origin, prefix_ok)
+
+
+#: The root name, '.'
+root = Name([b""])
+
+#: The empty name.
+empty = Name([])
+
+
+def from_unicode(
+ text: str, origin: Optional[Name] = root, idna_codec: Optional[IDNACodec] = None
+) -> Name:
+ """Convert unicode text into a Name object.
+
+ Labels are encoded in IDN ACE form according to rules specified by
+ the IDNA codec.
+
+ *text*, a ``str``, is the text to convert into a name.
+
+ *origin*, a ``dns.name.Name``, specifies the origin to
+ append to non-absolute names. The default is the root name.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if not isinstance(text, str):
+ raise ValueError("input to from_unicode() must be a unicode string")
+ if not (origin is None or isinstance(origin, Name)):
+ raise ValueError("origin must be a Name or None")
+ labels = []
+ label = ""
+ escaping = False
+ edigits = 0
+ total = 0
+ if idna_codec is None:
+ idna_codec = IDNA_2003
+ if text == "@":
+ text = ""
+ if text:
+ if text in [".", "\u3002", "\uff0e", "\uff61"]:
+ return Name([b""]) # no Unicode "u" on this constant!
+ for c in text:
+ if escaping:
+ if edigits == 0:
+ if c.isdigit():
+ total = int(c)
+ edigits += 1
+ else:
+ label += c
+ escaping = False
+ else:
+ if not c.isdigit():
+ raise BadEscape
+ total *= 10
+ total += int(c)
+ edigits += 1
+ if edigits == 3:
+ escaping = False
+ label += chr(total)
+ elif c in [".", "\u3002", "\uff0e", "\uff61"]:
+ if len(label) == 0:
+ raise EmptyLabel
+ labels.append(idna_codec.encode(label))
+ label = ""
+ elif c == "\\":
+ escaping = True
+ edigits = 0
+ total = 0
+ else:
+ label += c
+ if escaping:
+ raise BadEscape
+ if len(label) > 0:
+ labels.append(idna_codec.encode(label))
+ else:
+ labels.append(b"")
+
+ if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
+ labels.extend(list(origin.labels))
+ return Name(labels)
+
+
+def is_all_ascii(text: str) -> bool:
+ for c in text:
+ if ord(c) > 0x7F:
+ return False
+ return True
+
+
+def from_text(
+ text: Union[bytes, str],
+ origin: Optional[Name] = root,
+ idna_codec: Optional[IDNACodec] = None,
+) -> Name:
+ """Convert text into a Name object.
+
+ *text*, a ``bytes`` or ``str``, is the text to convert into a name.
+
+ *origin*, a ``dns.name.Name``, specifies the origin to
+ append to non-absolute names. The default is the root name.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if isinstance(text, str):
+ if not is_all_ascii(text):
+ # Some codepoint in the input text is > 127, so IDNA applies.
+ return from_unicode(text, origin, idna_codec)
+ # The input is all ASCII, so treat this like an ordinary non-IDNA
+ # domain name. Note that "all ASCII" is about the input text,
+ # not the codepoints in the domain name. E.g. if text has value
+ #
+ # r'\150\151\152\153\154\155\156\157\158\159'
+ #
+ # then it's still "all ASCII" even though the domain name has
+ # codepoints > 127.
+ text = text.encode("ascii")
+ if not isinstance(text, bytes):
+ raise ValueError("input to from_text() must be a string")
+ if not (origin is None or isinstance(origin, Name)):
+ raise ValueError("origin must be a Name or None")
+ labels = []
+ label = b""
+ escaping = False
+ edigits = 0
+ total = 0
+ if text == b"@":
+ text = b""
+ if text:
+ if text == b".":
+ return Name([b""])
+ for c in text:
+ byte_ = struct.pack("!B", c)
+ if escaping:
+ if edigits == 0:
+ if byte_.isdigit():
+ total = int(byte_)
+ edigits += 1
+ else:
+ label += byte_
+ escaping = False
+ else:
+ if not byte_.isdigit():
+ raise BadEscape
+ total *= 10
+ total += int(byte_)
+ edigits += 1
+ if edigits == 3:
+ escaping = False
+ label += struct.pack("!B", total)
+ elif byte_ == b".":
+ if len(label) == 0:
+ raise EmptyLabel
+ labels.append(label)
+ label = b""
+ elif byte_ == b"\\":
+ escaping = True
+ edigits = 0
+ total = 0
+ else:
+ label += byte_
+ if escaping:
+ raise BadEscape
+ if len(label) > 0:
+ labels.append(label)
+ else:
+ labels.append(b"")
+ if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
+ labels.extend(list(origin.labels))
+ return Name(labels)
+
+
+# we need 'dns.wire.Parser' quoted as dns.name and dns.wire depend on each other.
+
+
+def from_wire_parser(parser: "dns.wire.Parser") -> Name:
+ """Convert possibly compressed wire format into a Name.
+
+ *parser* is a dns.wire.Parser.
+
+ Raises ``dns.name.BadPointer`` if a compression pointer did not
+ point backwards in the message.
+
+ Raises ``dns.name.BadLabelType`` if an invalid label type was encountered.
+
+ Returns a ``dns.name.Name``
+ """
+
+ labels = []
+ biggest_pointer = parser.current
+ with parser.restore_furthest():
+ count = parser.get_uint8()
+ while count != 0:
+ if count < 64:
+ labels.append(parser.get_bytes(count))
+ elif count >= 192:
+ current = (count & 0x3F) * 256 + parser.get_uint8()
+ if current >= biggest_pointer:
+ raise BadPointer
+ biggest_pointer = current
+ parser.seek(current)
+ else:
+ raise BadLabelType
+ count = parser.get_uint8()
+ labels.append(b"")
+ return Name(labels)
+
+
+def from_wire(message: bytes, current: int) -> Tuple[Name, int]:
+ """Convert possibly compressed wire format into a Name.
+
+ *message* is a ``bytes`` containing an entire DNS message in DNS
+ wire form.
+
+ *current*, an ``int``, is the offset of the beginning of the name
+ from the start of the message
+
+ Raises ``dns.name.BadPointer`` if a compression pointer did not
+ point backwards in the message.
+
+ Raises ``dns.name.BadLabelType`` if an invalid label type was encountered.
+
+ Returns a ``(dns.name.Name, int)`` tuple consisting of the name
+ that was read and the number of bytes of the wire format message
+ which were consumed reading it.
+ """
+
+ if not isinstance(message, bytes):
+ raise ValueError("input to from_wire() must be a byte string")
+ parser = dns.wire.Parser(message, current)
+ name = from_wire_parser(parser)
+ return (name, parser.current - current)
+
+
+# RFC 4471 Support
+
+_MINIMAL_OCTET = b"\x00"
+_MINIMAL_OCTET_VALUE = ord(_MINIMAL_OCTET)
+_SUCCESSOR_PREFIX = Name([_MINIMAL_OCTET])
+_MAXIMAL_OCTET = b"\xff"
+_MAXIMAL_OCTET_VALUE = ord(_MAXIMAL_OCTET)
+_AT_SIGN_VALUE = ord("@")
+_LEFT_SQUARE_BRACKET_VALUE = ord("[")
+
+
+def _wire_length(labels):
+ return functools.reduce(lambda v, x: v + len(x) + 1, labels, 0)
+
+
+def _pad_to_max_name(name):
+ needed = 255 - _wire_length(name.labels)
+ new_labels = []
+ while needed > 64:
+ new_labels.append(_MAXIMAL_OCTET * 63)
+ needed -= 64
+ if needed >= 2:
+ new_labels.append(_MAXIMAL_OCTET * (needed - 1))
+ # Note we're already maximal in the needed == 1 case as while we'd like
+ # to add one more byte as a new label, we can't, as adding a new non-empty
+ # label requires at least 2 bytes.
+ new_labels = list(reversed(new_labels))
+ new_labels.extend(name.labels)
+ return Name(new_labels)
+
+
+def _pad_to_max_label(label, suffix_labels):
+ length = len(label)
+ # We have to subtract one here to account for the length byte of label.
+ remaining = 255 - _wire_length(suffix_labels) - length - 1
+ if remaining <= 0:
+ # Shouldn't happen!
+ return label
+ needed = min(63 - length, remaining)
+ return label + _MAXIMAL_OCTET * needed
+
+
+def _absolute_predecessor(name: Name, origin: Name, prefix_ok: bool) -> Name:
+ # This is the RFC 4471 predecessor algorithm using the "absolute method" of section
+ # 3.1.1.
+ #
+ # Our caller must ensure that the name and origin are absolute, and that name is a
+ # subdomain of origin.
+ if name == origin:
+ return _pad_to_max_name(name)
+ least_significant_label = name[0]
+ if least_significant_label == _MINIMAL_OCTET:
+ return name.parent()
+ least_octet = least_significant_label[-1]
+ suffix_labels = name.labels[1:]
+ if least_octet == _MINIMAL_OCTET_VALUE:
+ new_labels = [least_significant_label[:-1]]
+ else:
+ octets = bytearray(least_significant_label)
+ octet = octets[-1]
+ if octet == _LEFT_SQUARE_BRACKET_VALUE:
+ octet = _AT_SIGN_VALUE
+ else:
+ octet -= 1
+ octets[-1] = octet
+ least_significant_label = bytes(octets)
+ new_labels = [_pad_to_max_label(least_significant_label, suffix_labels)]
+ new_labels.extend(suffix_labels)
+ name = Name(new_labels)
+ if prefix_ok:
+ return _pad_to_max_name(name)
+ else:
+ return name
+
+
+def _absolute_successor(name: Name, origin: Name, prefix_ok: bool) -> Name:
+ # This is the RFC 4471 successor algorithm using the "absolute method" of section
+ # 3.1.2.
+ #
+ # Our caller must ensure that the name and origin are absolute, and that name is a
+ # subdomain of origin.
+ if prefix_ok:
+ # Try prefixing \000 as new label
+ try:
+ return _SUCCESSOR_PREFIX.concatenate(name)
+ except NameTooLong:
+ pass
+ while name != origin:
+ # Try extending the least significant label.
+ least_significant_label = name[0]
+ if len(least_significant_label) < 63:
+ # We may be able to extend the least label with a minimal additional byte.
+ # This is only "may" because we could have a maximal length name even though
+ # the least significant label isn't maximally long.
+ new_labels = [least_significant_label + _MINIMAL_OCTET]
+ new_labels.extend(name.labels[1:])
+ try:
+ return dns.name.Name(new_labels)
+ except dns.name.NameTooLong:
+ pass
+ # We can't extend the label either, so we'll try to increment the least
+ # signficant non-maximal byte in it.
+ octets = bytearray(least_significant_label)
+ # We do this reversed iteration with an explicit indexing variable because
+ # if we find something to increment, we're going to want to truncate everything
+ # to the right of it.
+ for i in range(len(octets) - 1, -1, -1):
+ octet = octets[i]
+ if octet == _MAXIMAL_OCTET_VALUE:
+ # We can't increment this, so keep looking.
+ continue
+ # Finally, something we can increment. We have to apply a special rule for
+ # incrementing "@", sending it to "[", because RFC 4034 6.1 says that when
+ # comparing names, uppercase letters compare as if they were their
+ # lower-case equivalents. If we increment "@" to "A", then it would compare
+ # as "a", which is after "[", "\", "]", "^", "_", and "`", so we would have
+ # skipped the most minimal successor, namely "[".
+ if octet == _AT_SIGN_VALUE:
+ octet = _LEFT_SQUARE_BRACKET_VALUE
+ else:
+ octet += 1
+ octets[i] = octet
+ # We can now truncate all of the maximal values we skipped (if any)
+ new_labels = [bytes(octets[: i + 1])]
+ new_labels.extend(name.labels[1:])
+ # We haven't changed the length of the name, so the Name constructor will
+ # always work.
+ return Name(new_labels)
+ # We couldn't increment, so chop off the least significant label and try
+ # again.
+ name = name.parent()
+
+ # We couldn't increment at all, so return the origin, as wrapping around is the
+ # DNSSEC way.
+ return origin
+
+
+def _handle_relativity_and_call(
+ function: Callable[[Name, Name, bool], Name],
+ name: Name,
+ origin: Name,
+ prefix_ok: bool,
+) -> Name:
+ # Make "name" absolute if needed, ensure that the origin is absolute,
+ # call function(), and then relativize the result if needed.
+ if not origin.is_absolute():
+ raise NeedAbsoluteNameOrOrigin
+ relative = not name.is_absolute()
+ if relative:
+ name = name.derelativize(origin)
+ elif not name.is_subdomain(origin):
+ raise NeedSubdomainOfOrigin
+ result_name = function(name, origin, prefix_ok)
+ if relative:
+ result_name = result_name.relativize(origin)
+ return result_name
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/namedict.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/namedict.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca8b19789b86a3482110b48d532999bb4cf277b7
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/namedict.py
@@ -0,0 +1,109 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+# Copyright (C) 2016 Coresec Systems AB
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND CORESEC SYSTEMS AB DISCLAIMS ALL
+# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL CORESEC
+# SYSTEMS AB BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
+# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS name dictionary"""
+
+# pylint seems to be confused about this one!
+from collections.abc import MutableMapping # pylint: disable=no-name-in-module
+
+import dns.name
+
+
+class NameDict(MutableMapping):
+ """A dictionary whose keys are dns.name.Name objects.
+
+ In addition to being like a regular Python dictionary, this
+ dictionary can also get the deepest match for a given key.
+ """
+
+ __slots__ = ["max_depth", "max_depth_items", "__store"]
+
+ def __init__(self, *args, **kwargs):
+ super().__init__()
+ self.__store = dict()
+ #: the maximum depth of the keys that have ever been added
+ self.max_depth = 0
+ #: the number of items of maximum depth
+ self.max_depth_items = 0
+ self.update(dict(*args, **kwargs))
+
+ def __update_max_depth(self, key):
+ if len(key) == self.max_depth:
+ self.max_depth_items = self.max_depth_items + 1
+ elif len(key) > self.max_depth:
+ self.max_depth = len(key)
+ self.max_depth_items = 1
+
+ def __getitem__(self, key):
+ return self.__store[key]
+
+ def __setitem__(self, key, value):
+ if not isinstance(key, dns.name.Name):
+ raise ValueError("NameDict key must be a name")
+ self.__store[key] = value
+ self.__update_max_depth(key)
+
+ def __delitem__(self, key):
+ self.__store.pop(key)
+ if len(key) == self.max_depth:
+ self.max_depth_items = self.max_depth_items - 1
+ if self.max_depth_items == 0:
+ self.max_depth = 0
+ for k in self.__store:
+ self.__update_max_depth(k)
+
+ def __iter__(self):
+ return iter(self.__store)
+
+ def __len__(self):
+ return len(self.__store)
+
+ def has_key(self, key):
+ return key in self.__store
+
+ def get_deepest_match(self, name):
+ """Find the deepest match to *name* in the dictionary.
+
+ The deepest match is the longest name in the dictionary which is
+ a superdomain of *name*. Note that *superdomain* includes matching
+ *name* itself.
+
+ *name*, a ``dns.name.Name``, the name to find.
+
+ Returns a ``(key, value)`` where *key* is the deepest
+ ``dns.name.Name``, and *value* is the value associated with *key*.
+ """
+
+ depth = len(name)
+ if depth > self.max_depth:
+ depth = self.max_depth
+ for i in range(-depth, 0):
+ n = dns.name.Name(name[i:])
+ if n in self:
+ return (n, self[n])
+ v = self[dns.name.empty]
+ return (dns.name.empty, v)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/nameserver.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/nameserver.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dbb4e8baf00a4086f54ee6b796de6a89e462fb2
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/nameserver.py
@@ -0,0 +1,359 @@
+from typing import Optional, Union
+from urllib.parse import urlparse
+
+import dns.asyncbackend
+import dns.asyncquery
+import dns.inet
+import dns.message
+import dns.query
+
+
+class Nameserver:
+ def __init__(self):
+ pass
+
+ def __str__(self):
+ raise NotImplementedError
+
+ def kind(self) -> str:
+ raise NotImplementedError
+
+ def is_always_max_size(self) -> bool:
+ raise NotImplementedError
+
+ def answer_nameserver(self) -> str:
+ raise NotImplementedError
+
+ def answer_port(self) -> int:
+ raise NotImplementedError
+
+ def query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ raise NotImplementedError
+
+ async def async_query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool,
+ backend: dns.asyncbackend.Backend,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ raise NotImplementedError
+
+
+class AddressAndPortNameserver(Nameserver):
+ def __init__(self, address: str, port: int):
+ super().__init__()
+ self.address = address
+ self.port = port
+
+ def kind(self) -> str:
+ raise NotImplementedError
+
+ def is_always_max_size(self) -> bool:
+ return False
+
+ def __str__(self):
+ ns_kind = self.kind()
+ return f"{ns_kind}:{self.address}@{self.port}"
+
+ def answer_nameserver(self) -> str:
+ return self.address
+
+ def answer_port(self) -> int:
+ return self.port
+
+
+class Do53Nameserver(AddressAndPortNameserver):
+ def __init__(self, address: str, port: int = 53):
+ super().__init__(address, port)
+
+ def kind(self):
+ return "Do53"
+
+ def query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ if max_size:
+ response = dns.query.tcp(
+ request,
+ self.address,
+ timeout=timeout,
+ port=self.port,
+ source=source,
+ source_port=source_port,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ else:
+ response = dns.query.udp(
+ request,
+ self.address,
+ timeout=timeout,
+ port=self.port,
+ source=source,
+ source_port=source_port,
+ raise_on_truncation=True,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ ignore_errors=True,
+ ignore_unexpected=True,
+ )
+ return response
+
+ async def async_query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool,
+ backend: dns.asyncbackend.Backend,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ if max_size:
+ response = await dns.asyncquery.tcp(
+ request,
+ self.address,
+ timeout=timeout,
+ port=self.port,
+ source=source,
+ source_port=source_port,
+ backend=backend,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ else:
+ response = await dns.asyncquery.udp(
+ request,
+ self.address,
+ timeout=timeout,
+ port=self.port,
+ source=source,
+ source_port=source_port,
+ raise_on_truncation=True,
+ backend=backend,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ ignore_errors=True,
+ ignore_unexpected=True,
+ )
+ return response
+
+
+class DoHNameserver(Nameserver):
+ def __init__(
+ self,
+ url: str,
+ bootstrap_address: Optional[str] = None,
+ verify: Union[bool, str] = True,
+ want_get: bool = False,
+ ):
+ super().__init__()
+ self.url = url
+ self.bootstrap_address = bootstrap_address
+ self.verify = verify
+ self.want_get = want_get
+
+ def kind(self):
+ return "DoH"
+
+ def is_always_max_size(self) -> bool:
+ return True
+
+ def __str__(self):
+ return self.url
+
+ def answer_nameserver(self) -> str:
+ return self.url
+
+ def answer_port(self) -> int:
+ port = urlparse(self.url).port
+ if port is None:
+ port = 443
+ return port
+
+ def query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ return dns.query.https(
+ request,
+ self.url,
+ timeout=timeout,
+ source=source,
+ source_port=source_port,
+ bootstrap_address=self.bootstrap_address,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ verify=self.verify,
+ post=(not self.want_get),
+ )
+
+ async def async_query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool,
+ backend: dns.asyncbackend.Backend,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ return await dns.asyncquery.https(
+ request,
+ self.url,
+ timeout=timeout,
+ source=source,
+ source_port=source_port,
+ bootstrap_address=self.bootstrap_address,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ verify=self.verify,
+ post=(not self.want_get),
+ )
+
+
+class DoTNameserver(AddressAndPortNameserver):
+ def __init__(
+ self,
+ address: str,
+ port: int = 853,
+ hostname: Optional[str] = None,
+ verify: Union[bool, str] = True,
+ ):
+ super().__init__(address, port)
+ self.hostname = hostname
+ self.verify = verify
+
+ def kind(self):
+ return "DoT"
+
+ def query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ return dns.query.tls(
+ request,
+ self.address,
+ port=self.port,
+ timeout=timeout,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ server_hostname=self.hostname,
+ verify=self.verify,
+ )
+
+ async def async_query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool,
+ backend: dns.asyncbackend.Backend,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ return await dns.asyncquery.tls(
+ request,
+ self.address,
+ port=self.port,
+ timeout=timeout,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ server_hostname=self.hostname,
+ verify=self.verify,
+ )
+
+
+class DoQNameserver(AddressAndPortNameserver):
+ def __init__(
+ self,
+ address: str,
+ port: int = 853,
+ verify: Union[bool, str] = True,
+ server_hostname: Optional[str] = None,
+ ):
+ super().__init__(address, port)
+ self.verify = verify
+ self.server_hostname = server_hostname
+
+ def kind(self):
+ return "DoQ"
+
+ def query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ return dns.query.quic(
+ request,
+ self.address,
+ port=self.port,
+ timeout=timeout,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ verify=self.verify,
+ server_hostname=self.server_hostname,
+ )
+
+ async def async_query(
+ self,
+ request: dns.message.QueryMessage,
+ timeout: float,
+ source: Optional[str],
+ source_port: int,
+ max_size: bool,
+ backend: dns.asyncbackend.Backend,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ ) -> dns.message.Message:
+ return await dns.asyncquery.quic(
+ request,
+ self.address,
+ port=self.port,
+ timeout=timeout,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ verify=self.verify,
+ server_hostname=self.server_hostname,
+ )
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/node.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/node.py
new file mode 100644
index 0000000000000000000000000000000000000000..de85a82d8c643156a804f07b994d7febcf2123a5
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/node.py
@@ -0,0 +1,359 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS nodes. A node is a set of rdatasets."""
+
+import enum
+import io
+from typing import Any, Dict, Optional
+
+import dns.immutable
+import dns.name
+import dns.rdataclass
+import dns.rdataset
+import dns.rdatatype
+import dns.renderer
+import dns.rrset
+
+_cname_types = {
+ dns.rdatatype.CNAME,
+}
+
+# "neutral" types can coexist with a CNAME and thus are not "other data"
+_neutral_types = {
+ dns.rdatatype.NSEC, # RFC 4035 section 2.5
+ dns.rdatatype.NSEC3, # This is not likely to happen, but not impossible!
+ dns.rdatatype.KEY, # RFC 4035 section 2.5, RFC 3007
+}
+
+
+def _matches_type_or_its_signature(rdtypes, rdtype, covers):
+ return rdtype in rdtypes or (rdtype == dns.rdatatype.RRSIG and covers in rdtypes)
+
+
+@enum.unique
+class NodeKind(enum.Enum):
+ """Rdatasets in nodes"""
+
+ REGULAR = 0 # a.k.a "other data"
+ NEUTRAL = 1
+ CNAME = 2
+
+ @classmethod
+ def classify(
+ cls, rdtype: dns.rdatatype.RdataType, covers: dns.rdatatype.RdataType
+ ) -> "NodeKind":
+ if _matches_type_or_its_signature(_cname_types, rdtype, covers):
+ return NodeKind.CNAME
+ elif _matches_type_or_its_signature(_neutral_types, rdtype, covers):
+ return NodeKind.NEUTRAL
+ else:
+ return NodeKind.REGULAR
+
+ @classmethod
+ def classify_rdataset(cls, rdataset: dns.rdataset.Rdataset) -> "NodeKind":
+ return cls.classify(rdataset.rdtype, rdataset.covers)
+
+
+class Node:
+ """A Node is a set of rdatasets.
+
+ A node is either a CNAME node or an "other data" node. A CNAME
+ node contains only CNAME, KEY, NSEC, and NSEC3 rdatasets along with their
+ covering RRSIG rdatasets. An "other data" node contains any
+ rdataset other than a CNAME or RRSIG(CNAME) rdataset. When
+ changes are made to a node, the CNAME or "other data" state is
+ always consistent with the update, i.e. the most recent change
+ wins. For example, if you have a node which contains a CNAME
+ rdataset, and then add an MX rdataset to it, then the CNAME
+ rdataset will be deleted. Likewise if you have a node containing
+ an MX rdataset and add a CNAME rdataset, the MX rdataset will be
+ deleted.
+ """
+
+ __slots__ = ["rdatasets"]
+
+ def __init__(self):
+ # the set of rdatasets, represented as a list.
+ self.rdatasets = []
+
+ def to_text(self, name: dns.name.Name, **kw: Dict[str, Any]) -> str:
+ """Convert a node to text format.
+
+ Each rdataset at the node is printed. Any keyword arguments
+ to this method are passed on to the rdataset's to_text() method.
+
+ *name*, a ``dns.name.Name``, the owner name of the
+ rdatasets.
+
+ Returns a ``str``.
+
+ """
+
+ s = io.StringIO()
+ for rds in self.rdatasets:
+ if len(rds) > 0:
+ s.write(rds.to_text(name, **kw)) # type: ignore[arg-type]
+ s.write("\n")
+ return s.getvalue()[:-1]
+
+ def __repr__(self):
+ return ""
+
+ def __eq__(self, other):
+ #
+ # This is inefficient. Good thing we don't need to do it much.
+ #
+ for rd in self.rdatasets:
+ if rd not in other.rdatasets:
+ return False
+ for rd in other.rdatasets:
+ if rd not in self.rdatasets:
+ return False
+ return True
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __len__(self):
+ return len(self.rdatasets)
+
+ def __iter__(self):
+ return iter(self.rdatasets)
+
+ def _append_rdataset(self, rdataset):
+ """Append rdataset to the node with special handling for CNAME and
+ other data conditions.
+
+ Specifically, if the rdataset being appended has ``NodeKind.CNAME``,
+ then all rdatasets other than KEY, NSEC, NSEC3, and their covering
+ RRSIGs are deleted. If the rdataset being appended has
+ ``NodeKind.REGULAR`` then CNAME and RRSIG(CNAME) are deleted.
+ """
+ # Make having just one rdataset at the node fast.
+ if len(self.rdatasets) > 0:
+ kind = NodeKind.classify_rdataset(rdataset)
+ if kind == NodeKind.CNAME:
+ self.rdatasets = [
+ rds
+ for rds in self.rdatasets
+ if NodeKind.classify_rdataset(rds) != NodeKind.REGULAR
+ ]
+ elif kind == NodeKind.REGULAR:
+ self.rdatasets = [
+ rds
+ for rds in self.rdatasets
+ if NodeKind.classify_rdataset(rds) != NodeKind.CNAME
+ ]
+ # Otherwise the rdataset is NodeKind.NEUTRAL and we do not need to
+ # edit self.rdatasets.
+ self.rdatasets.append(rdataset)
+
+ def find_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> dns.rdataset.Rdataset:
+ """Find an rdataset matching the specified properties in the
+ current node.
+
+ *rdclass*, a ``dns.rdataclass.RdataClass``, the class of the rdataset.
+
+ *rdtype*, a ``dns.rdatatype.RdataType``, the type of the rdataset.
+
+ *covers*, a ``dns.rdatatype.RdataType``, the covered type.
+ Usually this value is ``dns.rdatatype.NONE``, but if the
+ rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
+ then the covers value will be the rdata type the SIG/RRSIG
+ covers. The library treats the SIG and RRSIG types as if they
+ were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
+ This makes RRSIGs much easier to work with than if RRSIGs
+ covering different rdata types were aggregated into a single
+ RRSIG rdataset.
+
+ *create*, a ``bool``. If True, create the rdataset if it is not found.
+
+ Raises ``KeyError`` if an rdataset of the desired type and class does
+ not exist and *create* is not ``True``.
+
+ Returns a ``dns.rdataset.Rdataset``.
+ """
+
+ for rds in self.rdatasets:
+ if rds.match(rdclass, rdtype, covers):
+ return rds
+ if not create:
+ raise KeyError
+ rds = dns.rdataset.Rdataset(rdclass, rdtype, covers)
+ self._append_rdataset(rds)
+ return rds
+
+ def get_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> Optional[dns.rdataset.Rdataset]:
+ """Get an rdataset matching the specified properties in the
+ current node.
+
+ None is returned if an rdataset of the specified type and
+ class does not exist and *create* is not ``True``.
+
+ *rdclass*, an ``int``, the class of the rdataset.
+
+ *rdtype*, an ``int``, the type of the rdataset.
+
+ *covers*, an ``int``, the covered type. Usually this value is
+ dns.rdatatype.NONE, but if the rdtype is dns.rdatatype.SIG or
+ dns.rdatatype.RRSIG, then the covers value will be the rdata
+ type the SIG/RRSIG covers. The library treats the SIG and RRSIG
+ types as if they were a family of
+ types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This makes RRSIGs much
+ easier to work with than if RRSIGs covering different rdata
+ types were aggregated into a single RRSIG rdataset.
+
+ *create*, a ``bool``. If True, create the rdataset if it is not found.
+
+ Returns a ``dns.rdataset.Rdataset`` or ``None``.
+ """
+
+ try:
+ rds = self.find_rdataset(rdclass, rdtype, covers, create)
+ except KeyError:
+ rds = None
+ return rds
+
+ def delete_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ ) -> None:
+ """Delete the rdataset matching the specified properties in the
+ current node.
+
+ If a matching rdataset does not exist, it is not an error.
+
+ *rdclass*, an ``int``, the class of the rdataset.
+
+ *rdtype*, an ``int``, the type of the rdataset.
+
+ *covers*, an ``int``, the covered type.
+ """
+
+ rds = self.get_rdataset(rdclass, rdtype, covers)
+ if rds is not None:
+ self.rdatasets.remove(rds)
+
+ def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None:
+ """Replace an rdataset.
+
+ It is not an error if there is no rdataset matching *replacement*.
+
+ Ownership of the *replacement* object is transferred to the node;
+ in other words, this method does not store a copy of *replacement*
+ at the node, it stores *replacement* itself.
+
+ *replacement*, a ``dns.rdataset.Rdataset``.
+
+ Raises ``ValueError`` if *replacement* is not a
+ ``dns.rdataset.Rdataset``.
+ """
+
+ if not isinstance(replacement, dns.rdataset.Rdataset):
+ raise ValueError("replacement is not an rdataset")
+ if isinstance(replacement, dns.rrset.RRset):
+ # RRsets are not good replacements as the match() method
+ # is not compatible.
+ replacement = replacement.to_rdataset()
+ self.delete_rdataset(
+ replacement.rdclass, replacement.rdtype, replacement.covers
+ )
+ self._append_rdataset(replacement)
+
+ def classify(self) -> NodeKind:
+ """Classify a node.
+
+ A node which contains a CNAME or RRSIG(CNAME) is a
+ ``NodeKind.CNAME`` node.
+
+ A node which contains only "neutral" types, i.e. types allowed to
+ co-exist with a CNAME, is a ``NodeKind.NEUTRAL`` node. The neutral
+ types are NSEC, NSEC3, KEY, and their associated RRSIGS. An empty node
+ is also considered neutral.
+
+ A node which contains some rdataset which is not a CNAME, RRSIG(CNAME),
+ or a neutral type is a a ``NodeKind.REGULAR`` node. Regular nodes are
+ also commonly referred to as "other data".
+ """
+ for rdataset in self.rdatasets:
+ kind = NodeKind.classify(rdataset.rdtype, rdataset.covers)
+ if kind != NodeKind.NEUTRAL:
+ return kind
+ return NodeKind.NEUTRAL
+
+ def is_immutable(self) -> bool:
+ return False
+
+
+@dns.immutable.immutable
+class ImmutableNode(Node):
+ def __init__(self, node):
+ super().__init__()
+ self.rdatasets = tuple(
+ [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets]
+ )
+
+ def find_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> dns.rdataset.Rdataset:
+ if create:
+ raise TypeError("immutable")
+ return super().find_rdataset(rdclass, rdtype, covers, False)
+
+ def get_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> Optional[dns.rdataset.Rdataset]:
+ if create:
+ raise TypeError("immutable")
+ return super().get_rdataset(rdclass, rdtype, covers, False)
+
+ def delete_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ ) -> None:
+ raise TypeError("immutable")
+
+ def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None:
+ raise TypeError("immutable")
+
+ def is_immutable(self) -> bool:
+ return True
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/opcode.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/opcode.py
new file mode 100644
index 0000000000000000000000000000000000000000..78b43d2cbd1404b57f683b2bfad7f726e99caffd
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/opcode.py
@@ -0,0 +1,117 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Opcodes."""
+
+import dns.enum
+import dns.exception
+
+
+class Opcode(dns.enum.IntEnum):
+ #: Query
+ QUERY = 0
+ #: Inverse Query (historical)
+ IQUERY = 1
+ #: Server Status (unspecified and unimplemented anywhere)
+ STATUS = 2
+ #: Notify
+ NOTIFY = 4
+ #: Dynamic Update
+ UPDATE = 5
+
+ @classmethod
+ def _maximum(cls):
+ return 15
+
+ @classmethod
+ def _unknown_exception_class(cls):
+ return UnknownOpcode
+
+
+class UnknownOpcode(dns.exception.DNSException):
+ """An DNS opcode is unknown."""
+
+
+def from_text(text: str) -> Opcode:
+ """Convert text into an opcode.
+
+ *text*, a ``str``, the textual opcode
+
+ Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown.
+
+ Returns an ``int``.
+ """
+
+ return Opcode.from_text(text)
+
+
+def from_flags(flags: int) -> Opcode:
+ """Extract an opcode from DNS message flags.
+
+ *flags*, an ``int``, the DNS flags.
+
+ Returns an ``int``.
+ """
+
+ return Opcode((flags & 0x7800) >> 11)
+
+
+def to_flags(value: Opcode) -> int:
+ """Convert an opcode to a value suitable for ORing into DNS message
+ flags.
+
+ *value*, an ``int``, the DNS opcode value.
+
+ Returns an ``int``.
+ """
+
+ return (value << 11) & 0x7800
+
+
+def to_text(value: Opcode) -> str:
+ """Convert an opcode to text.
+
+ *value*, an ``int`` the opcode value,
+
+ Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown.
+
+ Returns a ``str``.
+ """
+
+ return Opcode.to_text(value)
+
+
+def is_update(flags: int) -> bool:
+ """Is the opcode in flags UPDATE?
+
+ *flags*, an ``int``, the DNS message flags.
+
+ Returns a ``bool``.
+ """
+
+ return from_flags(flags) == Opcode.UPDATE
+
+
+### BEGIN generated Opcode constants
+
+QUERY = Opcode.QUERY
+IQUERY = Opcode.IQUERY
+STATUS = Opcode.STATUS
+NOTIFY = Opcode.NOTIFY
+UPDATE = Opcode.UPDATE
+
+### END generated Opcode constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/py.typed b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/query.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/query.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0ee9161f532bdc0211fd75c8cf2ccb654fe08d8
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/query.py
@@ -0,0 +1,1578 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Talk to a DNS server."""
+
+import base64
+import contextlib
+import enum
+import errno
+import os
+import os.path
+import selectors
+import socket
+import struct
+import time
+from typing import Any, Dict, Optional, Tuple, Union
+
+import dns._features
+import dns.exception
+import dns.inet
+import dns.message
+import dns.name
+import dns.quic
+import dns.rcode
+import dns.rdataclass
+import dns.rdatatype
+import dns.serial
+import dns.transaction
+import dns.tsig
+import dns.xfr
+
+
+def _remaining(expiration):
+ if expiration is None:
+ return None
+ timeout = expiration - time.time()
+ if timeout <= 0.0:
+ raise dns.exception.Timeout
+ return timeout
+
+
+def _expiration_for_this_attempt(timeout, expiration):
+ if expiration is None:
+ return None
+ return min(time.time() + timeout, expiration)
+
+
+_have_httpx = dns._features.have("doh")
+if _have_httpx:
+ import httpcore._backends.sync
+ import httpx
+
+ _CoreNetworkBackend = httpcore.NetworkBackend
+ _CoreSyncStream = httpcore._backends.sync.SyncStream
+
+ class _NetworkBackend(_CoreNetworkBackend):
+ def __init__(self, resolver, local_port, bootstrap_address, family):
+ super().__init__()
+ self._local_port = local_port
+ self._resolver = resolver
+ self._bootstrap_address = bootstrap_address
+ self._family = family
+
+ def connect_tcp(
+ self, host, port, timeout, local_address, socket_options=None
+ ): # pylint: disable=signature-differs
+ addresses = []
+ _, expiration = _compute_times(timeout)
+ if dns.inet.is_address(host):
+ addresses.append(host)
+ elif self._bootstrap_address is not None:
+ addresses.append(self._bootstrap_address)
+ else:
+ timeout = _remaining(expiration)
+ family = self._family
+ if local_address:
+ family = dns.inet.af_for_address(local_address)
+ answers = self._resolver.resolve_name(
+ host, family=family, lifetime=timeout
+ )
+ addresses = answers.addresses()
+ for address in addresses:
+ af = dns.inet.af_for_address(address)
+ if local_address is not None or self._local_port != 0:
+ source = dns.inet.low_level_address_tuple(
+ (local_address, self._local_port), af
+ )
+ else:
+ source = None
+ sock = _make_socket(af, socket.SOCK_STREAM, source)
+ attempt_expiration = _expiration_for_this_attempt(2.0, expiration)
+ try:
+ _connect(
+ sock,
+ dns.inet.low_level_address_tuple((address, port), af),
+ attempt_expiration,
+ )
+ return _CoreSyncStream(sock)
+ except Exception:
+ pass
+ raise httpcore.ConnectError
+
+ def connect_unix_socket(
+ self, path, timeout, socket_options=None
+ ): # pylint: disable=signature-differs
+ raise NotImplementedError
+
+ class _HTTPTransport(httpx.HTTPTransport):
+ def __init__(
+ self,
+ *args,
+ local_port=0,
+ bootstrap_address=None,
+ resolver=None,
+ family=socket.AF_UNSPEC,
+ **kwargs,
+ ):
+ if resolver is None:
+ # pylint: disable=import-outside-toplevel,redefined-outer-name
+ import dns.resolver
+
+ resolver = dns.resolver.Resolver()
+ super().__init__(*args, **kwargs)
+ self._pool._network_backend = _NetworkBackend(
+ resolver, local_port, bootstrap_address, family
+ )
+
+else:
+
+ class _HTTPTransport: # type: ignore
+ def connect_tcp(self, host, port, timeout, local_address):
+ raise NotImplementedError
+
+
+have_doh = _have_httpx
+
+try:
+ import ssl
+except ImportError: # pragma: no cover
+
+ class ssl: # type: ignore
+ CERT_NONE = 0
+
+ class WantReadException(Exception):
+ pass
+
+ class WantWriteException(Exception):
+ pass
+
+ class SSLContext:
+ pass
+
+ class SSLSocket:
+ pass
+
+ @classmethod
+ def create_default_context(cls, *args, **kwargs):
+ raise Exception("no ssl support") # pylint: disable=broad-exception-raised
+
+
+# Function used to create a socket. Can be overridden if needed in special
+# situations.
+socket_factory = socket.socket
+
+
+class UnexpectedSource(dns.exception.DNSException):
+ """A DNS query response came from an unexpected address or port."""
+
+
+class BadResponse(dns.exception.FormError):
+ """A DNS query response does not respond to the question asked."""
+
+
+class NoDOH(dns.exception.DNSException):
+ """DNS over HTTPS (DOH) was requested but the httpx module is not
+ available."""
+
+
+class NoDOQ(dns.exception.DNSException):
+ """DNS over QUIC (DOQ) was requested but the aioquic module is not
+ available."""
+
+
+# for backwards compatibility
+TransferError = dns.xfr.TransferError
+
+
+def _compute_times(timeout):
+ now = time.time()
+ if timeout is None:
+ return (now, None)
+ else:
+ return (now, now + timeout)
+
+
+def _wait_for(fd, readable, writable, _, expiration):
+ # Use the selected selector class to wait for any of the specified
+ # events. An "expiration" absolute time is converted into a relative
+ # timeout.
+ #
+ # The unused parameter is 'error', which is always set when
+ # selecting for read or write, and we have no error-only selects.
+
+ if readable and isinstance(fd, ssl.SSLSocket) and fd.pending() > 0:
+ return True
+ sel = _selector_class()
+ events = 0
+ if readable:
+ events |= selectors.EVENT_READ
+ if writable:
+ events |= selectors.EVENT_WRITE
+ if events:
+ sel.register(fd, events)
+ if expiration is None:
+ timeout = None
+ else:
+ timeout = expiration - time.time()
+ if timeout <= 0.0:
+ raise dns.exception.Timeout
+ if not sel.select(timeout):
+ raise dns.exception.Timeout
+
+
+def _set_selector_class(selector_class):
+ # Internal API. Do not use.
+
+ global _selector_class
+
+ _selector_class = selector_class
+
+
+if hasattr(selectors, "PollSelector"):
+ # Prefer poll() on platforms that support it because it has no
+ # limits on the maximum value of a file descriptor (plus it will
+ # be more efficient for high values).
+ #
+ # We ignore typing here as we can't say _selector_class is Any
+ # on python < 3.8 due to a bug.
+ _selector_class = selectors.PollSelector # type: ignore
+else:
+ _selector_class = selectors.SelectSelector # type: ignore
+
+
+def _wait_for_readable(s, expiration):
+ _wait_for(s, True, False, True, expiration)
+
+
+def _wait_for_writable(s, expiration):
+ _wait_for(s, False, True, True, expiration)
+
+
+def _addresses_equal(af, a1, a2):
+ # Convert the first value of the tuple, which is a textual format
+ # address into binary form, so that we are not confused by different
+ # textual representations of the same address
+ try:
+ n1 = dns.inet.inet_pton(af, a1[0])
+ n2 = dns.inet.inet_pton(af, a2[0])
+ except dns.exception.SyntaxError:
+ return False
+ return n1 == n2 and a1[1:] == a2[1:]
+
+
+def _matches_destination(af, from_address, destination, ignore_unexpected):
+ # Check that from_address is appropriate for a response to a query
+ # sent to destination.
+ if not destination:
+ return True
+ if _addresses_equal(af, from_address, destination) or (
+ dns.inet.is_multicast(destination[0]) and from_address[1:] == destination[1:]
+ ):
+ return True
+ elif ignore_unexpected:
+ return False
+ raise UnexpectedSource(
+ f"got a response from {from_address} instead of " f"{destination}"
+ )
+
+
+def _destination_and_source(
+ where, port, source, source_port, where_must_be_address=True
+):
+ # Apply defaults and compute destination and source tuples
+ # suitable for use in connect(), sendto(), or bind().
+ af = None
+ destination = None
+ try:
+ af = dns.inet.af_for_address(where)
+ destination = where
+ except Exception:
+ if where_must_be_address:
+ raise
+ # URLs are ok so eat the exception
+ if source:
+ saf = dns.inet.af_for_address(source)
+ if af:
+ # We know the destination af, so source had better agree!
+ if saf != af:
+ raise ValueError(
+ "different address families for source and destination"
+ )
+ else:
+ # We didn't know the destination af, but we know the source,
+ # so that's our af.
+ af = saf
+ if source_port and not source:
+ # Caller has specified a source_port but not an address, so we
+ # need to return a source, and we need to use the appropriate
+ # wildcard address as the address.
+ try:
+ source = dns.inet.any_for_af(af)
+ except Exception:
+ # we catch this and raise ValueError for backwards compatibility
+ raise ValueError("source_port specified but address family is unknown")
+ # Convert high-level (address, port) tuples into low-level address
+ # tuples.
+ if destination:
+ destination = dns.inet.low_level_address_tuple((destination, port), af)
+ if source:
+ source = dns.inet.low_level_address_tuple((source, source_port), af)
+ return (af, destination, source)
+
+
+def _make_socket(af, type, source, ssl_context=None, server_hostname=None):
+ s = socket_factory(af, type)
+ try:
+ s.setblocking(False)
+ if source is not None:
+ s.bind(source)
+ if ssl_context:
+ # LGTM gets a false positive here, as our default context is OK
+ return ssl_context.wrap_socket(
+ s,
+ do_handshake_on_connect=False, # lgtm[py/insecure-protocol]
+ server_hostname=server_hostname,
+ )
+ else:
+ return s
+ except Exception:
+ s.close()
+ raise
+
+
+def https(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 443,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ session: Optional[Any] = None,
+ path: str = "/dns-query",
+ post: bool = True,
+ bootstrap_address: Optional[str] = None,
+ verify: Union[bool, str] = True,
+ resolver: Optional["dns.resolver.Resolver"] = None,
+ family: Optional[int] = socket.AF_UNSPEC,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via DNS-over-HTTPS.
+
+ *q*, a ``dns.message.Message``, the query to send.
+
+ *where*, a ``str``, the nameserver IP address or the full URL. If an IP address is
+ given, the URL will be constructed using the following schema:
+ https://:/.
+
+ *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query
+ times out. If ``None``, the default, wait forever.
+
+ *port*, a ``int``, the port to send the query to. The default is 443.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source
+ address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message. The default is
+ 0.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
+ received message.
+
+ *session*, an ``httpx.Client``. If provided, the client session to use to send the
+ queries.
+
+ *path*, a ``str``. If *where* is an IP address, then *path* will be used to
+ construct the URL to send the DNS query to.
+
+ *post*, a ``bool``. If ``True``, the default, POST method will be used.
+
+ *bootstrap_address*, a ``str``, the IP address to use to bypass resolution.
+
+ *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification
+ of the server is done using the default CA bundle; if ``False``, then no
+ verification is done; if a `str` then it specifies the path to a certificate file or
+ directory which will be used for verification.
+
+ *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for
+ resolution of hostnames in URLs. If not specified, a new resolver with a default
+ configuration will be used; note this is *not* the default resolver as that resolver
+ might have been configured to use DoH causing a chicken-and-egg problem. This
+ parameter only has an effect if the HTTP library is httpx.
+
+ *family*, an ``int``, the address family. If socket.AF_UNSPEC (the default), both A
+ and AAAA records will be retrieved.
+
+ Returns a ``dns.message.Message``.
+ """
+
+ if not have_doh:
+ raise NoDOH # pragma: no cover
+ if session and not isinstance(session, httpx.Client):
+ raise ValueError("session parameter must be an httpx.Client")
+
+ wire = q.to_wire()
+ (af, _, the_source) = _destination_and_source(
+ where, port, source, source_port, False
+ )
+ transport = None
+ headers = {"accept": "application/dns-message"}
+ if af is not None and dns.inet.is_address(where):
+ if af == socket.AF_INET:
+ url = "https://{}:{}{}".format(where, port, path)
+ elif af == socket.AF_INET6:
+ url = "https://[{}]:{}{}".format(where, port, path)
+ else:
+ url = where
+
+ # set source port and source address
+
+ if the_source is None:
+ local_address = None
+ local_port = 0
+ else:
+ local_address = the_source[0]
+ local_port = the_source[1]
+ transport = _HTTPTransport(
+ local_address=local_address,
+ http1=True,
+ http2=True,
+ verify=verify,
+ local_port=local_port,
+ bootstrap_address=bootstrap_address,
+ resolver=resolver,
+ family=family,
+ )
+
+ if session:
+ cm: contextlib.AbstractContextManager = contextlib.nullcontext(session)
+ else:
+ cm = httpx.Client(http1=True, http2=True, verify=verify, transport=transport)
+ with cm as session:
+ # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH
+ # GET and POST examples
+ if post:
+ headers.update(
+ {
+ "content-type": "application/dns-message",
+ "content-length": str(len(wire)),
+ }
+ )
+ response = session.post(url, headers=headers, content=wire, timeout=timeout)
+ else:
+ wire = base64.urlsafe_b64encode(wire).rstrip(b"=")
+ twire = wire.decode() # httpx does a repr() if we give it bytes
+ response = session.get(
+ url, headers=headers, timeout=timeout, params={"dns": twire}
+ )
+
+ # see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH
+ # status codes
+ if response.status_code < 200 or response.status_code > 299:
+ raise ValueError(
+ "{} responded with status code {}"
+ "\nResponse body: {}".format(where, response.status_code, response.content)
+ )
+ r = dns.message.from_wire(
+ response.content,
+ keyring=q.keyring,
+ request_mac=q.request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ r.time = response.elapsed.total_seconds()
+ if not q.is_response(r):
+ raise BadResponse
+ return r
+
+
+def _udp_recv(sock, max_size, expiration):
+ """Reads a datagram from the socket.
+ A Timeout exception will be raised if the operation is not completed
+ by the expiration time.
+ """
+ while True:
+ try:
+ return sock.recvfrom(max_size)
+ except BlockingIOError:
+ _wait_for_readable(sock, expiration)
+
+
+def _udp_send(sock, data, destination, expiration):
+ """Sends the specified datagram to destination over the socket.
+ A Timeout exception will be raised if the operation is not completed
+ by the expiration time.
+ """
+ while True:
+ try:
+ if destination:
+ return sock.sendto(data, destination)
+ else:
+ return sock.send(data)
+ except BlockingIOError: # pragma: no cover
+ _wait_for_writable(sock, expiration)
+
+
+def send_udp(
+ sock: Any,
+ what: Union[dns.message.Message, bytes],
+ destination: Any,
+ expiration: Optional[float] = None,
+) -> Tuple[int, float]:
+ """Send a DNS message to the specified UDP socket.
+
+ *sock*, a ``socket``.
+
+ *what*, a ``bytes`` or ``dns.message.Message``, the message to send.
+
+ *destination*, a destination tuple appropriate for the address family
+ of the socket, specifying where to send the query.
+
+ *expiration*, a ``float`` or ``None``, the absolute time at which
+ a timeout exception should be raised. If ``None``, no timeout will
+ occur.
+
+ Returns an ``(int, float)`` tuple of bytes sent and the sent time.
+ """
+
+ if isinstance(what, dns.message.Message):
+ what = what.to_wire()
+ sent_time = time.time()
+ n = _udp_send(sock, what, destination, expiration)
+ return (n, sent_time)
+
+
+def receive_udp(
+ sock: Any,
+ destination: Optional[Any] = None,
+ expiration: Optional[float] = None,
+ ignore_unexpected: bool = False,
+ one_rr_per_rrset: bool = False,
+ keyring: Optional[Dict[dns.name.Name, dns.tsig.Key]] = None,
+ request_mac: Optional[bytes] = b"",
+ ignore_trailing: bool = False,
+ raise_on_truncation: bool = False,
+ ignore_errors: bool = False,
+ query: Optional[dns.message.Message] = None,
+) -> Any:
+ """Read a DNS message from a UDP socket.
+
+ *sock*, a ``socket``.
+
+ *destination*, a destination tuple appropriate for the address family
+ of the socket, specifying where the message is expected to arrive from.
+ When receiving a response, this would be where the associated query was
+ sent.
+
+ *expiration*, a ``float`` or ``None``, the absolute time at which
+ a timeout exception should be raised. If ``None``, no timeout will
+ occur.
+
+ *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from
+ unexpected sources.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
+ RRset.
+
+ *keyring*, a ``dict``, the keyring to use for TSIG.
+
+ *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG).
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
+ junk at end of the received message.
+
+ *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if
+ the TC bit is set.
+
+ Raises if the message is malformed, if network errors occur, of if
+ there is a timeout.
+
+ If *destination* is not ``None``, returns a ``(dns.message.Message, float)``
+ tuple of the received message and the received time.
+
+ If *destination* is ``None``, returns a
+ ``(dns.message.Message, float, tuple)``
+ tuple of the received message, the received time, and the address where
+ the message arrived from.
+
+ *ignore_errors*, a ``bool``. If various format errors or response
+ mismatches occur, ignore them and keep listening for a valid response.
+ The default is ``False``.
+
+ *query*, a ``dns.message.Message`` or ``None``. If not ``None`` and
+ *ignore_errors* is ``True``, check that the received message is a response
+ to this query, and if not keep listening for a valid response.
+ """
+
+ wire = b""
+ while True:
+ (wire, from_address) = _udp_recv(sock, 65535, expiration)
+ if not _matches_destination(
+ sock.family, from_address, destination, ignore_unexpected
+ ):
+ continue
+ received_time = time.time()
+ try:
+ r = dns.message.from_wire(
+ wire,
+ keyring=keyring,
+ request_mac=request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ raise_on_truncation=raise_on_truncation,
+ )
+ except dns.message.Truncated as e:
+ # If we got Truncated and not FORMERR, we at least got the header with TC
+ # set, and very likely the question section, so we'll re-raise if the
+ # message seems to be a response as we need to know when truncation happens.
+ # We need to check that it seems to be a response as we don't want a random
+ # injected message with TC set to cause us to bail out.
+ if (
+ ignore_errors
+ and query is not None
+ and not query.is_response(e.message())
+ ):
+ continue
+ else:
+ raise
+ except Exception:
+ if ignore_errors:
+ continue
+ else:
+ raise
+ if ignore_errors and query is not None and not query.is_response(r):
+ continue
+ if destination:
+ return (r, received_time)
+ else:
+ return (r, received_time, from_address)
+
+
+def udp(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 53,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ ignore_unexpected: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ raise_on_truncation: bool = False,
+ sock: Optional[Any] = None,
+ ignore_errors: bool = False,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via UDP.
+
+ *q*, a ``dns.message.Message``, the query to send
+
+ *where*, a ``str`` containing an IPv4 or IPv6 address, where
+ to send the message.
+
+ *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
+ query times out. If ``None``, the default, wait forever.
+
+ *port*, an ``int``, the port send the message to. The default is 53.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
+ the source address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message.
+ The default is 0.
+
+ *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from
+ unexpected sources.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
+ RRset.
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
+ junk at end of the received message.
+
+ *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if
+ the TC bit is set.
+
+ *sock*, a ``socket.socket``, or ``None``, the socket to use for the
+ query. If ``None``, the default, a socket is created. Note that
+ if a socket is provided, it must be a nonblocking datagram socket,
+ and the *source* and *source_port* are ignored.
+
+ *ignore_errors*, a ``bool``. If various format errors or response
+ mismatches occur, ignore them and keep listening for a valid response.
+ The default is ``False``.
+
+ Returns a ``dns.message.Message``.
+ """
+
+ wire = q.to_wire()
+ (af, destination, source) = _destination_and_source(
+ where, port, source, source_port
+ )
+ (begin_time, expiration) = _compute_times(timeout)
+ if sock:
+ cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock)
+ else:
+ cm = _make_socket(af, socket.SOCK_DGRAM, source)
+ with cm as s:
+ send_udp(s, wire, destination, expiration)
+ (r, received_time) = receive_udp(
+ s,
+ destination,
+ expiration,
+ ignore_unexpected,
+ one_rr_per_rrset,
+ q.keyring,
+ q.mac,
+ ignore_trailing,
+ raise_on_truncation,
+ ignore_errors,
+ q,
+ )
+ r.time = received_time - begin_time
+ # We don't need to check q.is_response() if we are in ignore_errors mode
+ # as receive_udp() will have checked it.
+ if not (ignore_errors or q.is_response(r)):
+ raise BadResponse
+ return r
+ assert (
+ False # help mypy figure out we can't get here lgtm[py/unreachable-statement]
+ )
+
+
+def udp_with_fallback(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 53,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ ignore_unexpected: bool = False,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ udp_sock: Optional[Any] = None,
+ tcp_sock: Optional[Any] = None,
+ ignore_errors: bool = False,
+) -> Tuple[dns.message.Message, bool]:
+ """Return the response to the query, trying UDP first and falling back
+ to TCP if UDP results in a truncated response.
+
+ *q*, a ``dns.message.Message``, the query to send
+
+ *where*, a ``str`` containing an IPv4 or IPv6 address, where to send the message.
+
+ *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query
+ times out. If ``None``, the default, wait forever.
+
+ *port*, an ``int``, the port send the message to. The default is 53.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source
+ address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message. The default is
+ 0.
+
+ *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from unexpected
+ sources.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
+ received message.
+
+ *udp_sock*, a ``socket.socket``, or ``None``, the socket to use for the UDP query.
+ If ``None``, the default, a socket is created. Note that if a socket is provided,
+ it must be a nonblocking datagram socket, and the *source* and *source_port* are
+ ignored for the UDP query.
+
+ *tcp_sock*, a ``socket.socket``, or ``None``, the connected socket to use for the
+ TCP query. If ``None``, the default, a socket is created. Note that if a socket is
+ provided, it must be a nonblocking connected stream socket, and *where*, *source*
+ and *source_port* are ignored for the TCP query.
+
+ *ignore_errors*, a ``bool``. If various format errors or response mismatches occur
+ while listening for UDP, ignore them and keep listening for a valid response. The
+ default is ``False``.
+
+ Returns a (``dns.message.Message``, tcp) tuple where tcp is ``True`` if and only if
+ TCP was used.
+ """
+ try:
+ response = udp(
+ q,
+ where,
+ timeout,
+ port,
+ source,
+ source_port,
+ ignore_unexpected,
+ one_rr_per_rrset,
+ ignore_trailing,
+ True,
+ udp_sock,
+ ignore_errors,
+ )
+ return (response, False)
+ except dns.message.Truncated:
+ response = tcp(
+ q,
+ where,
+ timeout,
+ port,
+ source,
+ source_port,
+ one_rr_per_rrset,
+ ignore_trailing,
+ tcp_sock,
+ )
+ return (response, True)
+
+
+def _net_read(sock, count, expiration):
+ """Read the specified number of bytes from sock. Keep trying until we
+ either get the desired amount, or we hit EOF.
+ A Timeout exception will be raised if the operation is not completed
+ by the expiration time.
+ """
+ s = b""
+ while count > 0:
+ try:
+ n = sock.recv(count)
+ if n == b"":
+ raise EOFError
+ count -= len(n)
+ s += n
+ except (BlockingIOError, ssl.SSLWantReadError):
+ _wait_for_readable(sock, expiration)
+ except ssl.SSLWantWriteError: # pragma: no cover
+ _wait_for_writable(sock, expiration)
+ return s
+
+
+def _net_write(sock, data, expiration):
+ """Write the specified data to the socket.
+ A Timeout exception will be raised if the operation is not completed
+ by the expiration time.
+ """
+ current = 0
+ l = len(data)
+ while current < l:
+ try:
+ current += sock.send(data[current:])
+ except (BlockingIOError, ssl.SSLWantWriteError):
+ _wait_for_writable(sock, expiration)
+ except ssl.SSLWantReadError: # pragma: no cover
+ _wait_for_readable(sock, expiration)
+
+
+def send_tcp(
+ sock: Any,
+ what: Union[dns.message.Message, bytes],
+ expiration: Optional[float] = None,
+) -> Tuple[int, float]:
+ """Send a DNS message to the specified TCP socket.
+
+ *sock*, a ``socket``.
+
+ *what*, a ``bytes`` or ``dns.message.Message``, the message to send.
+
+ *expiration*, a ``float`` or ``None``, the absolute time at which
+ a timeout exception should be raised. If ``None``, no timeout will
+ occur.
+
+ Returns an ``(int, float)`` tuple of bytes sent and the sent time.
+ """
+
+ if isinstance(what, dns.message.Message):
+ tcpmsg = what.to_wire(prepend_length=True)
+ else:
+ # copying the wire into tcpmsg is inefficient, but lets us
+ # avoid writev() or doing a short write that would get pushed
+ # onto the net
+ tcpmsg = len(what).to_bytes(2, "big") + what
+ sent_time = time.time()
+ _net_write(sock, tcpmsg, expiration)
+ return (len(tcpmsg), sent_time)
+
+
+def receive_tcp(
+ sock: Any,
+ expiration: Optional[float] = None,
+ one_rr_per_rrset: bool = False,
+ keyring: Optional[Dict[dns.name.Name, dns.tsig.Key]] = None,
+ request_mac: Optional[bytes] = b"",
+ ignore_trailing: bool = False,
+) -> Tuple[dns.message.Message, float]:
+ """Read a DNS message from a TCP socket.
+
+ *sock*, a ``socket``.
+
+ *expiration*, a ``float`` or ``None``, the absolute time at which
+ a timeout exception should be raised. If ``None``, no timeout will
+ occur.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
+ RRset.
+
+ *keyring*, a ``dict``, the keyring to use for TSIG.
+
+ *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG).
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
+ junk at end of the received message.
+
+ Raises if the message is malformed, if network errors occur, of if
+ there is a timeout.
+
+ Returns a ``(dns.message.Message, float)`` tuple of the received message
+ and the received time.
+ """
+
+ ldata = _net_read(sock, 2, expiration)
+ (l,) = struct.unpack("!H", ldata)
+ wire = _net_read(sock, l, expiration)
+ received_time = time.time()
+ r = dns.message.from_wire(
+ wire,
+ keyring=keyring,
+ request_mac=request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ return (r, received_time)
+
+
+def _connect(s, address, expiration):
+ err = s.connect_ex(address)
+ if err == 0:
+ return
+ if err in (errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY):
+ _wait_for_writable(s, expiration)
+ err = s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
+ if err != 0:
+ raise OSError(err, os.strerror(err))
+
+
+def tcp(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 53,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ sock: Optional[Any] = None,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via TCP.
+
+ *q*, a ``dns.message.Message``, the query to send
+
+ *where*, a ``str`` containing an IPv4 or IPv6 address, where
+ to send the message.
+
+ *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
+ query times out. If ``None``, the default, wait forever.
+
+ *port*, an ``int``, the port send the message to. The default is 53.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
+ the source address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message.
+ The default is 0.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
+ RRset.
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
+ junk at end of the received message.
+
+ *sock*, a ``socket.socket``, or ``None``, the connected socket to use for the
+ query. If ``None``, the default, a socket is created. Note that
+ if a socket is provided, it must be a nonblocking connected stream
+ socket, and *where*, *port*, *source* and *source_port* are ignored.
+
+ Returns a ``dns.message.Message``.
+ """
+
+ wire = q.to_wire()
+ (begin_time, expiration) = _compute_times(timeout)
+ if sock:
+ cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock)
+ else:
+ (af, destination, source) = _destination_and_source(
+ where, port, source, source_port
+ )
+ cm = _make_socket(af, socket.SOCK_STREAM, source)
+ with cm as s:
+ if not sock:
+ _connect(s, destination, expiration)
+ send_tcp(s, wire, expiration)
+ (r, received_time) = receive_tcp(
+ s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing
+ )
+ r.time = received_time - begin_time
+ if not q.is_response(r):
+ raise BadResponse
+ return r
+ assert (
+ False # help mypy figure out we can't get here lgtm[py/unreachable-statement]
+ )
+
+
+def _tls_handshake(s, expiration):
+ while True:
+ try:
+ s.do_handshake()
+ return
+ except ssl.SSLWantReadError:
+ _wait_for_readable(s, expiration)
+ except ssl.SSLWantWriteError: # pragma: no cover
+ _wait_for_writable(s, expiration)
+
+
+def _make_dot_ssl_context(
+ server_hostname: Optional[str], verify: Union[bool, str]
+) -> ssl.SSLContext:
+ cafile: Optional[str] = None
+ capath: Optional[str] = None
+ if isinstance(verify, str):
+ if os.path.isfile(verify):
+ cafile = verify
+ elif os.path.isdir(verify):
+ capath = verify
+ else:
+ raise ValueError("invalid verify string")
+ ssl_context = ssl.create_default_context(cafile=cafile, capath=capath)
+ ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
+ if server_hostname is None:
+ ssl_context.check_hostname = False
+ ssl_context.set_alpn_protocols(["dot"])
+ if verify is False:
+ ssl_context.verify_mode = ssl.CERT_NONE
+ return ssl_context
+
+
+def tls(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 853,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ sock: Optional[ssl.SSLSocket] = None,
+ ssl_context: Optional[ssl.SSLContext] = None,
+ server_hostname: Optional[str] = None,
+ verify: Union[bool, str] = True,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via TLS.
+
+ *q*, a ``dns.message.Message``, the query to send
+
+ *where*, a ``str`` containing an IPv4 or IPv6 address, where
+ to send the message.
+
+ *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
+ query times out. If ``None``, the default, wait forever.
+
+ *port*, an ``int``, the port send the message to. The default is 853.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
+ the source address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message.
+ The default is 0.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
+ RRset.
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
+ junk at end of the received message.
+
+ *sock*, an ``ssl.SSLSocket``, or ``None``, the socket to use for
+ the query. If ``None``, the default, a socket is created. Note
+ that if a socket is provided, it must be a nonblocking connected
+ SSL stream socket, and *where*, *port*, *source*, *source_port*,
+ and *ssl_context* are ignored.
+
+ *ssl_context*, an ``ssl.SSLContext``, the context to use when establishing
+ a TLS connection. If ``None``, the default, creates one with the default
+ configuration.
+
+ *server_hostname*, a ``str`` containing the server's hostname. The
+ default is ``None``, which means that no hostname is known, and if an
+ SSL context is created, hostname checking will be disabled.
+
+ *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification
+ of the server is done using the default CA bundle; if ``False``, then no
+ verification is done; if a `str` then it specifies the path to a certificate file or
+ directory which will be used for verification.
+
+ Returns a ``dns.message.Message``.
+
+ """
+
+ if sock:
+ #
+ # If a socket was provided, there's no special TLS handling needed.
+ #
+ return tcp(
+ q,
+ where,
+ timeout,
+ port,
+ source,
+ source_port,
+ one_rr_per_rrset,
+ ignore_trailing,
+ sock,
+ )
+
+ wire = q.to_wire()
+ (begin_time, expiration) = _compute_times(timeout)
+ (af, destination, source) = _destination_and_source(
+ where, port, source, source_port
+ )
+ if ssl_context is None and not sock:
+ ssl_context = _make_dot_ssl_context(server_hostname, verify)
+
+ with _make_socket(
+ af,
+ socket.SOCK_STREAM,
+ source,
+ ssl_context=ssl_context,
+ server_hostname=server_hostname,
+ ) as s:
+ _connect(s, destination, expiration)
+ _tls_handshake(s, expiration)
+ send_tcp(s, wire, expiration)
+ (r, received_time) = receive_tcp(
+ s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing
+ )
+ r.time = received_time - begin_time
+ if not q.is_response(r):
+ raise BadResponse
+ return r
+ assert (
+ False # help mypy figure out we can't get here lgtm[py/unreachable-statement]
+ )
+
+
+def quic(
+ q: dns.message.Message,
+ where: str,
+ timeout: Optional[float] = None,
+ port: int = 853,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ one_rr_per_rrset: bool = False,
+ ignore_trailing: bool = False,
+ connection: Optional[dns.quic.SyncQuicConnection] = None,
+ verify: Union[bool, str] = True,
+ server_hostname: Optional[str] = None,
+) -> dns.message.Message:
+ """Return the response obtained after sending a query via DNS-over-QUIC.
+
+ *q*, a ``dns.message.Message``, the query to send.
+
+ *where*, a ``str``, the nameserver IP address.
+
+ *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query
+ times out. If ``None``, the default, wait forever.
+
+ *port*, a ``int``, the port to send the query to. The default is 853.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source
+ address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message. The default is
+ 0.
+
+ *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
+
+ *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
+ received message.
+
+ *connection*, a ``dns.quic.SyncQuicConnection``. If provided, the
+ connection to use to send the query.
+
+ *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification
+ of the server is done using the default CA bundle; if ``False``, then no
+ verification is done; if a `str` then it specifies the path to a certificate file or
+ directory which will be used for verification.
+
+ *server_hostname*, a ``str`` containing the server's hostname. The
+ default is ``None``, which means that no hostname is known, and if an
+ SSL context is created, hostname checking will be disabled.
+
+ Returns a ``dns.message.Message``.
+ """
+
+ if not dns.quic.have_quic:
+ raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover
+
+ q.id = 0
+ wire = q.to_wire()
+ the_connection: dns.quic.SyncQuicConnection
+ the_manager: dns.quic.SyncQuicManager
+ if connection:
+ manager: contextlib.AbstractContextManager = contextlib.nullcontext(None)
+ the_connection = connection
+ else:
+ manager = dns.quic.SyncQuicManager(
+ verify_mode=verify, server_name=server_hostname
+ )
+ the_manager = manager # for type checking happiness
+
+ with manager:
+ if not connection:
+ the_connection = the_manager.connect(where, port, source, source_port)
+ (start, expiration) = _compute_times(timeout)
+ with the_connection.make_stream(timeout) as stream:
+ stream.send(wire, True)
+ wire = stream.receive(_remaining(expiration))
+ finish = time.time()
+ r = dns.message.from_wire(
+ wire,
+ keyring=q.keyring,
+ request_mac=q.request_mac,
+ one_rr_per_rrset=one_rr_per_rrset,
+ ignore_trailing=ignore_trailing,
+ )
+ r.time = max(finish - start, 0.0)
+ if not q.is_response(r):
+ raise BadResponse
+ return r
+
+
+def xfr(
+ where: str,
+ zone: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.AXFR,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ timeout: Optional[float] = None,
+ port: int = 53,
+ keyring: Optional[Dict[dns.name.Name, dns.tsig.Key]] = None,
+ keyname: Optional[Union[dns.name.Name, str]] = None,
+ relativize: bool = True,
+ lifetime: Optional[float] = None,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ serial: int = 0,
+ use_udp: bool = False,
+ keyalgorithm: Union[dns.name.Name, str] = dns.tsig.default_algorithm,
+) -> Any:
+ """Return a generator for the responses to a zone transfer.
+
+ *where*, a ``str`` containing an IPv4 or IPv6 address, where
+ to send the message.
+
+ *zone*, a ``dns.name.Name`` or ``str``, the name of the zone to transfer.
+
+ *rdtype*, an ``int`` or ``str``, the type of zone transfer. The
+ default is ``dns.rdatatype.AXFR``. ``dns.rdatatype.IXFR`` can be
+ used to do an incremental transfer instead.
+
+ *rdclass*, an ``int`` or ``str``, the class of the zone transfer.
+ The default is ``dns.rdataclass.IN``.
+
+ *timeout*, a ``float``, the number of seconds to wait for each
+ response message. If None, the default, wait forever.
+
+ *port*, an ``int``, the port send the message to. The default is 53.
+
+ *keyring*, a ``dict``, the keyring to use for TSIG.
+
+ *keyname*, a ``dns.name.Name`` or ``str``, the name of the TSIG
+ key to use.
+
+ *relativize*, a ``bool``. If ``True``, all names in the zone will be
+ relativized to the zone origin. It is essential that the
+ relativize setting matches the one specified to
+ ``dns.zone.from_xfr()`` if using this generator to make a zone.
+
+ *lifetime*, a ``float``, the total number of seconds to spend
+ doing the transfer. If ``None``, the default, then there is no
+ limit on the time the transfer may take.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
+ the source address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message.
+ The default is 0.
+
+ *serial*, an ``int``, the SOA serial number to use as the base for
+ an IXFR diff sequence (only meaningful if *rdtype* is
+ ``dns.rdatatype.IXFR``).
+
+ *use_udp*, a ``bool``. If ``True``, use UDP (only meaningful for IXFR).
+
+ *keyalgorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use.
+
+ Raises on errors, and so does the generator.
+
+ Returns a generator of ``dns.message.Message`` objects.
+ """
+
+ if isinstance(zone, str):
+ zone = dns.name.from_text(zone)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ q = dns.message.make_query(zone, rdtype, rdclass)
+ if rdtype == dns.rdatatype.IXFR:
+ rrset = dns.rrset.from_text(zone, 0, "IN", "SOA", ". . %u 0 0 0 0" % serial)
+ q.authority.append(rrset)
+ if keyring is not None:
+ q.use_tsig(keyring, keyname, algorithm=keyalgorithm)
+ wire = q.to_wire()
+ (af, destination, source) = _destination_and_source(
+ where, port, source, source_port
+ )
+ if use_udp and rdtype != dns.rdatatype.IXFR:
+ raise ValueError("cannot do a UDP AXFR")
+ sock_type = socket.SOCK_DGRAM if use_udp else socket.SOCK_STREAM
+ with _make_socket(af, sock_type, source) as s:
+ (_, expiration) = _compute_times(lifetime)
+ _connect(s, destination, expiration)
+ l = len(wire)
+ if use_udp:
+ _udp_send(s, wire, None, expiration)
+ else:
+ tcpmsg = struct.pack("!H", l) + wire
+ _net_write(s, tcpmsg, expiration)
+ done = False
+ delete_mode = True
+ expecting_SOA = False
+ soa_rrset = None
+ if relativize:
+ origin = zone
+ oname = dns.name.empty
+ else:
+ origin = None
+ oname = zone
+ tsig_ctx = None
+ while not done:
+ (_, mexpiration) = _compute_times(timeout)
+ if mexpiration is None or (
+ expiration is not None and mexpiration > expiration
+ ):
+ mexpiration = expiration
+ if use_udp:
+ (wire, _) = _udp_recv(s, 65535, mexpiration)
+ else:
+ ldata = _net_read(s, 2, mexpiration)
+ (l,) = struct.unpack("!H", ldata)
+ wire = _net_read(s, l, mexpiration)
+ is_ixfr = rdtype == dns.rdatatype.IXFR
+ r = dns.message.from_wire(
+ wire,
+ keyring=q.keyring,
+ request_mac=q.mac,
+ xfr=True,
+ origin=origin,
+ tsig_ctx=tsig_ctx,
+ multi=True,
+ one_rr_per_rrset=is_ixfr,
+ )
+ rcode = r.rcode()
+ if rcode != dns.rcode.NOERROR:
+ raise TransferError(rcode)
+ tsig_ctx = r.tsig_ctx
+ answer_index = 0
+ if soa_rrset is None:
+ if not r.answer or r.answer[0].name != oname:
+ raise dns.exception.FormError("No answer or RRset not for qname")
+ rrset = r.answer[0]
+ if rrset.rdtype != dns.rdatatype.SOA:
+ raise dns.exception.FormError("first RRset is not an SOA")
+ answer_index = 1
+ soa_rrset = rrset.copy()
+ if rdtype == dns.rdatatype.IXFR:
+ if dns.serial.Serial(soa_rrset[0].serial) <= serial:
+ #
+ # We're already up-to-date.
+ #
+ done = True
+ else:
+ expecting_SOA = True
+ #
+ # Process SOAs in the answer section (other than the initial
+ # SOA in the first message).
+ #
+ for rrset in r.answer[answer_index:]:
+ if done:
+ raise dns.exception.FormError("answers after final SOA")
+ if rrset.rdtype == dns.rdatatype.SOA and rrset.name == oname:
+ if expecting_SOA:
+ if rrset[0].serial != serial:
+ raise dns.exception.FormError("IXFR base serial mismatch")
+ expecting_SOA = False
+ elif rdtype == dns.rdatatype.IXFR:
+ delete_mode = not delete_mode
+ #
+ # If this SOA RRset is equal to the first we saw then we're
+ # finished. If this is an IXFR we also check that we're
+ # seeing the record in the expected part of the response.
+ #
+ if rrset == soa_rrset and (
+ rdtype == dns.rdatatype.AXFR
+ or (rdtype == dns.rdatatype.IXFR and delete_mode)
+ ):
+ done = True
+ elif expecting_SOA:
+ #
+ # We made an IXFR request and are expecting another
+ # SOA RR, but saw something else, so this must be an
+ # AXFR response.
+ #
+ rdtype = dns.rdatatype.AXFR
+ expecting_SOA = False
+ if done and q.keyring and not r.had_tsig:
+ raise dns.exception.FormError("missing TSIG")
+ yield r
+
+
+class UDPMode(enum.IntEnum):
+ """How should UDP be used in an IXFR from :py:func:`inbound_xfr()`?
+
+ NEVER means "never use UDP; always use TCP"
+ TRY_FIRST means "try to use UDP but fall back to TCP if needed"
+ ONLY means "raise ``dns.xfr.UseTCP`` if trying UDP does not succeed"
+ """
+
+ NEVER = 0
+ TRY_FIRST = 1
+ ONLY = 2
+
+
+def inbound_xfr(
+ where: str,
+ txn_manager: dns.transaction.TransactionManager,
+ query: Optional[dns.message.Message] = None,
+ port: int = 53,
+ timeout: Optional[float] = None,
+ lifetime: Optional[float] = None,
+ source: Optional[str] = None,
+ source_port: int = 0,
+ udp_mode: UDPMode = UDPMode.NEVER,
+) -> None:
+ """Conduct an inbound transfer and apply it via a transaction from the
+ txn_manager.
+
+ *where*, a ``str`` containing an IPv4 or IPv6 address, where
+ to send the message.
+
+ *txn_manager*, a ``dns.transaction.TransactionManager``, the txn_manager
+ for this transfer (typically a ``dns.zone.Zone``).
+
+ *query*, the query to send. If not supplied, a default query is
+ constructed using information from the *txn_manager*.
+
+ *port*, an ``int``, the port send the message to. The default is 53.
+
+ *timeout*, a ``float``, the number of seconds to wait for each
+ response message. If None, the default, wait forever.
+
+ *lifetime*, a ``float``, the total number of seconds to spend
+ doing the transfer. If ``None``, the default, then there is no
+ limit on the time the transfer may take.
+
+ *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
+ the source address. The default is the wildcard address.
+
+ *source_port*, an ``int``, the port from which to send the message.
+ The default is 0.
+
+ *udp_mode*, a ``dns.query.UDPMode``, determines how UDP is used
+ for IXFRs. The default is ``dns.UDPMode.NEVER``, i.e. only use
+ TCP. Other possibilities are ``dns.UDPMode.TRY_FIRST``, which
+ means "try UDP but fallback to TCP if needed", and
+ ``dns.UDPMode.ONLY``, which means "try UDP and raise
+ ``dns.xfr.UseTCP`` if it does not succeed.
+
+ Raises on errors.
+ """
+ if query is None:
+ (query, serial) = dns.xfr.make_query(txn_manager)
+ else:
+ serial = dns.xfr.extract_serial_from_query(query)
+ rdtype = query.question[0].rdtype
+ is_ixfr = rdtype == dns.rdatatype.IXFR
+ origin = txn_manager.from_wire_origin()
+ wire = query.to_wire()
+ (af, destination, source) = _destination_and_source(
+ where, port, source, source_port
+ )
+ (_, expiration) = _compute_times(lifetime)
+ retry = True
+ while retry:
+ retry = False
+ if is_ixfr and udp_mode != UDPMode.NEVER:
+ sock_type = socket.SOCK_DGRAM
+ is_udp = True
+ else:
+ sock_type = socket.SOCK_STREAM
+ is_udp = False
+ with _make_socket(af, sock_type, source) as s:
+ _connect(s, destination, expiration)
+ if is_udp:
+ _udp_send(s, wire, None, expiration)
+ else:
+ tcpmsg = struct.pack("!H", len(wire)) + wire
+ _net_write(s, tcpmsg, expiration)
+ with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound:
+ done = False
+ tsig_ctx = None
+ while not done:
+ (_, mexpiration) = _compute_times(timeout)
+ if mexpiration is None or (
+ expiration is not None and mexpiration > expiration
+ ):
+ mexpiration = expiration
+ if is_udp:
+ (rwire, _) = _udp_recv(s, 65535, mexpiration)
+ else:
+ ldata = _net_read(s, 2, mexpiration)
+ (l,) = struct.unpack("!H", ldata)
+ rwire = _net_read(s, l, mexpiration)
+ r = dns.message.from_wire(
+ rwire,
+ keyring=query.keyring,
+ request_mac=query.mac,
+ xfr=True,
+ origin=origin,
+ tsig_ctx=tsig_ctx,
+ multi=(not is_udp),
+ one_rr_per_rrset=is_ixfr,
+ )
+ try:
+ done = inbound.process_message(r)
+ except dns.xfr.UseTCP:
+ assert is_udp # should not happen if we used TCP!
+ if udp_mode == UDPMode.ONLY:
+ raise
+ done = True
+ retry = True
+ udp_mode = UDPMode.NEVER
+ continue
+ tsig_ctx = r.tsig_ctx
+ if not retry and query.keyring and not r.had_tsig:
+ raise dns.exception.FormError("missing TSIG")
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rcode.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rcode.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e6386f828019b379bbe97a3950ce604c4778f7f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rcode.py
@@ -0,0 +1,168 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Result Codes."""
+
+from typing import Tuple
+
+import dns.enum
+import dns.exception
+
+
+class Rcode(dns.enum.IntEnum):
+ #: No error
+ NOERROR = 0
+ #: Format error
+ FORMERR = 1
+ #: Server failure
+ SERVFAIL = 2
+ #: Name does not exist ("Name Error" in RFC 1025 terminology).
+ NXDOMAIN = 3
+ #: Not implemented
+ NOTIMP = 4
+ #: Refused
+ REFUSED = 5
+ #: Name exists.
+ YXDOMAIN = 6
+ #: RRset exists.
+ YXRRSET = 7
+ #: RRset does not exist.
+ NXRRSET = 8
+ #: Not authoritative.
+ NOTAUTH = 9
+ #: Name not in zone.
+ NOTZONE = 10
+ #: DSO-TYPE Not Implemented
+ DSOTYPENI = 11
+ #: Bad EDNS version.
+ BADVERS = 16
+ #: TSIG Signature Failure
+ BADSIG = 16
+ #: Key not recognized.
+ BADKEY = 17
+ #: Signature out of time window.
+ BADTIME = 18
+ #: Bad TKEY Mode.
+ BADMODE = 19
+ #: Duplicate key name.
+ BADNAME = 20
+ #: Algorithm not supported.
+ BADALG = 21
+ #: Bad Truncation
+ BADTRUNC = 22
+ #: Bad/missing Server Cookie
+ BADCOOKIE = 23
+
+ @classmethod
+ def _maximum(cls):
+ return 4095
+
+ @classmethod
+ def _unknown_exception_class(cls):
+ return UnknownRcode
+
+
+class UnknownRcode(dns.exception.DNSException):
+ """A DNS rcode is unknown."""
+
+
+def from_text(text: str) -> Rcode:
+ """Convert text into an rcode.
+
+ *text*, a ``str``, the textual rcode or an integer in textual form.
+
+ Raises ``dns.rcode.UnknownRcode`` if the rcode mnemonic is unknown.
+
+ Returns a ``dns.rcode.Rcode``.
+ """
+
+ return Rcode.from_text(text)
+
+
+def from_flags(flags: int, ednsflags: int) -> Rcode:
+ """Return the rcode value encoded by flags and ednsflags.
+
+ *flags*, an ``int``, the DNS flags field.
+
+ *ednsflags*, an ``int``, the EDNS flags field.
+
+ Raises ``ValueError`` if rcode is < 0 or > 4095
+
+ Returns a ``dns.rcode.Rcode``.
+ """
+
+ value = (flags & 0x000F) | ((ednsflags >> 20) & 0xFF0)
+ return Rcode.make(value)
+
+
+def to_flags(value: Rcode) -> Tuple[int, int]:
+ """Return a (flags, ednsflags) tuple which encodes the rcode.
+
+ *value*, a ``dns.rcode.Rcode``, the rcode.
+
+ Raises ``ValueError`` if rcode is < 0 or > 4095.
+
+ Returns an ``(int, int)`` tuple.
+ """
+
+ if value < 0 or value > 4095:
+ raise ValueError("rcode must be >= 0 and <= 4095")
+ v = value & 0xF
+ ev = (value & 0xFF0) << 20
+ return (v, ev)
+
+
+def to_text(value: Rcode, tsig: bool = False) -> str:
+ """Convert rcode into text.
+
+ *value*, a ``dns.rcode.Rcode``, the rcode.
+
+ Raises ``ValueError`` if rcode is < 0 or > 4095.
+
+ Returns a ``str``.
+ """
+
+ if tsig and value == Rcode.BADVERS:
+ return "BADSIG"
+ return Rcode.to_text(value)
+
+
+### BEGIN generated Rcode constants
+
+NOERROR = Rcode.NOERROR
+FORMERR = Rcode.FORMERR
+SERVFAIL = Rcode.SERVFAIL
+NXDOMAIN = Rcode.NXDOMAIN
+NOTIMP = Rcode.NOTIMP
+REFUSED = Rcode.REFUSED
+YXDOMAIN = Rcode.YXDOMAIN
+YXRRSET = Rcode.YXRRSET
+NXRRSET = Rcode.NXRRSET
+NOTAUTH = Rcode.NOTAUTH
+NOTZONE = Rcode.NOTZONE
+DSOTYPENI = Rcode.DSOTYPENI
+BADVERS = Rcode.BADVERS
+BADSIG = Rcode.BADSIG
+BADKEY = Rcode.BADKEY
+BADTIME = Rcode.BADTIME
+BADMODE = Rcode.BADMODE
+BADNAME = Rcode.BADNAME
+BADALG = Rcode.BADALG
+BADTRUNC = Rcode.BADTRUNC
+BADCOOKIE = Rcode.BADCOOKIE
+
+### END generated Rcode constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdata.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdata.py
new file mode 100644
index 0000000000000000000000000000000000000000..024fd8f6872a23d18ad6fade67bb6279b2abca00
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdata.py
@@ -0,0 +1,884 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS rdata."""
+
+import base64
+import binascii
+import inspect
+import io
+import itertools
+import random
+from importlib import import_module
+from typing import Any, Dict, Optional, Tuple, Union
+
+import dns.exception
+import dns.immutable
+import dns.ipv4
+import dns.ipv6
+import dns.name
+import dns.rdataclass
+import dns.rdatatype
+import dns.tokenizer
+import dns.ttl
+import dns.wire
+
+_chunksize = 32
+
+# We currently allow comparisons for rdata with relative names for backwards
+# compatibility, but in the future we will not, as these kinds of comparisons
+# can lead to subtle bugs if code is not carefully written.
+#
+# This switch allows the future behavior to be turned on so code can be
+# tested with it.
+_allow_relative_comparisons = True
+
+
+class NoRelativeRdataOrdering(dns.exception.DNSException):
+ """An attempt was made to do an ordered comparison of one or more
+ rdata with relative names. The only reliable way of sorting rdata
+ is to use non-relativized rdata.
+
+ """
+
+
+def _wordbreak(data, chunksize=_chunksize, separator=b" "):
+ """Break a binary string into chunks of chunksize characters separated by
+ a space.
+ """
+
+ if not chunksize:
+ return data.decode()
+ return separator.join(
+ [data[i : i + chunksize] for i in range(0, len(data), chunksize)]
+ ).decode()
+
+
+# pylint: disable=unused-argument
+
+
+def _hexify(data, chunksize=_chunksize, separator=b" ", **kw):
+ """Convert a binary string into its hex encoding, broken up into chunks
+ of chunksize characters separated by a separator.
+ """
+
+ return _wordbreak(binascii.hexlify(data), chunksize, separator)
+
+
+def _base64ify(data, chunksize=_chunksize, separator=b" ", **kw):
+ """Convert a binary string into its base64 encoding, broken up into chunks
+ of chunksize characters separated by a separator.
+ """
+
+ return _wordbreak(base64.b64encode(data), chunksize, separator)
+
+
+# pylint: enable=unused-argument
+
+__escaped = b'"\\'
+
+
+def _escapify(qstring):
+ """Escape the characters in a quoted string which need it."""
+
+ if isinstance(qstring, str):
+ qstring = qstring.encode()
+ if not isinstance(qstring, bytearray):
+ qstring = bytearray(qstring)
+
+ text = ""
+ for c in qstring:
+ if c in __escaped:
+ text += "\\" + chr(c)
+ elif c >= 0x20 and c < 0x7F:
+ text += chr(c)
+ else:
+ text += "\\%03d" % c
+ return text
+
+
+def _truncate_bitmap(what):
+ """Determine the index of greatest byte that isn't all zeros, and
+ return the bitmap that contains all the bytes less than that index.
+ """
+
+ for i in range(len(what) - 1, -1, -1):
+ if what[i] != 0:
+ return what[0 : i + 1]
+ return what[0:1]
+
+
+# So we don't have to edit all the rdata classes...
+_constify = dns.immutable.constify
+
+
+@dns.immutable.immutable
+class Rdata:
+ """Base class for all DNS rdata types."""
+
+ __slots__ = ["rdclass", "rdtype", "rdcomment"]
+
+ def __init__(self, rdclass, rdtype):
+ """Initialize an rdata.
+
+ *rdclass*, an ``int`` is the rdataclass of the Rdata.
+
+ *rdtype*, an ``int`` is the rdatatype of the Rdata.
+ """
+
+ self.rdclass = self._as_rdataclass(rdclass)
+ self.rdtype = self._as_rdatatype(rdtype)
+ self.rdcomment = None
+
+ def _get_all_slots(self):
+ return itertools.chain.from_iterable(
+ getattr(cls, "__slots__", []) for cls in self.__class__.__mro__
+ )
+
+ def __getstate__(self):
+ # We used to try to do a tuple of all slots here, but it
+ # doesn't work as self._all_slots isn't available at
+ # __setstate__() time. Before that we tried to store a tuple
+ # of __slots__, but that didn't work as it didn't store the
+ # slots defined by ancestors. This older way didn't fail
+ # outright, but ended up with partially broken objects, e.g.
+ # if you unpickled an A RR it wouldn't have rdclass and rdtype
+ # attributes, and would compare badly.
+ state = {}
+ for slot in self._get_all_slots():
+ state[slot] = getattr(self, slot)
+ return state
+
+ def __setstate__(self, state):
+ for slot, val in state.items():
+ object.__setattr__(self, slot, val)
+ if not hasattr(self, "rdcomment"):
+ # Pickled rdata from 2.0.x might not have a rdcomment, so add
+ # it if needed.
+ object.__setattr__(self, "rdcomment", None)
+
+ def covers(self) -> dns.rdatatype.RdataType:
+ """Return the type a Rdata covers.
+
+ DNS SIG/RRSIG rdatas apply to a specific type; this type is
+ returned by the covers() function. If the rdata type is not
+ SIG or RRSIG, dns.rdatatype.NONE is returned. This is useful when
+ creating rdatasets, allowing the rdataset to contain only RRSIGs
+ of a particular type, e.g. RRSIG(NS).
+
+ Returns a ``dns.rdatatype.RdataType``.
+ """
+
+ return dns.rdatatype.NONE
+
+ def extended_rdatatype(self) -> int:
+ """Return a 32-bit type value, the least significant 16 bits of
+ which are the ordinary DNS type, and the upper 16 bits of which are
+ the "covered" type, if any.
+
+ Returns an ``int``.
+ """
+
+ return self.covers() << 16 | self.rdtype
+
+ def to_text(
+ self,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ **kw: Dict[str, Any],
+ ) -> str:
+ """Convert an rdata to text format.
+
+ Returns a ``str``.
+ """
+
+ raise NotImplementedError # pragma: no cover
+
+ def _to_wire(
+ self,
+ file: Optional[Any],
+ compress: Optional[dns.name.CompressType] = None,
+ origin: Optional[dns.name.Name] = None,
+ canonicalize: bool = False,
+ ) -> bytes:
+ raise NotImplementedError # pragma: no cover
+
+ def to_wire(
+ self,
+ file: Optional[Any] = None,
+ compress: Optional[dns.name.CompressType] = None,
+ origin: Optional[dns.name.Name] = None,
+ canonicalize: bool = False,
+ ) -> bytes:
+ """Convert an rdata to wire format.
+
+ Returns a ``bytes`` or ``None``.
+ """
+
+ if file:
+ return self._to_wire(file, compress, origin, canonicalize)
+ else:
+ f = io.BytesIO()
+ self._to_wire(f, compress, origin, canonicalize)
+ return f.getvalue()
+
+ def to_generic(
+ self, origin: Optional[dns.name.Name] = None
+ ) -> "dns.rdata.GenericRdata":
+ """Creates a dns.rdata.GenericRdata equivalent of this rdata.
+
+ Returns a ``dns.rdata.GenericRdata``.
+ """
+ return dns.rdata.GenericRdata(
+ self.rdclass, self.rdtype, self.to_wire(origin=origin)
+ )
+
+ def to_digestable(self, origin: Optional[dns.name.Name] = None) -> bytes:
+ """Convert rdata to a format suitable for digesting in hashes. This
+ is also the DNSSEC canonical form.
+
+ Returns a ``bytes``.
+ """
+
+ return self.to_wire(origin=origin, canonicalize=True)
+
+ def __repr__(self):
+ covers = self.covers()
+ if covers == dns.rdatatype.NONE:
+ ctext = ""
+ else:
+ ctext = "(" + dns.rdatatype.to_text(covers) + ")"
+ return (
+ ""
+ )
+
+ def __str__(self):
+ return self.to_text()
+
+ def _cmp(self, other):
+ """Compare an rdata with another rdata of the same rdtype and
+ rdclass.
+
+ For rdata with only absolute names:
+ Return < 0 if self < other in the DNSSEC ordering, 0 if self
+ == other, and > 0 if self > other.
+ For rdata with at least one relative names:
+ The rdata sorts before any rdata with only absolute names.
+ When compared with another relative rdata, all names are
+ made absolute as if they were relative to the root, as the
+ proper origin is not available. While this creates a stable
+ ordering, it is NOT guaranteed to be the DNSSEC ordering.
+ In the future, all ordering comparisons for rdata with
+ relative names will be disallowed.
+ """
+ try:
+ our = self.to_digestable()
+ our_relative = False
+ except dns.name.NeedAbsoluteNameOrOrigin:
+ if _allow_relative_comparisons:
+ our = self.to_digestable(dns.name.root)
+ our_relative = True
+ try:
+ their = other.to_digestable()
+ their_relative = False
+ except dns.name.NeedAbsoluteNameOrOrigin:
+ if _allow_relative_comparisons:
+ their = other.to_digestable(dns.name.root)
+ their_relative = True
+ if _allow_relative_comparisons:
+ if our_relative != their_relative:
+ # For the purpose of comparison, all rdata with at least one
+ # relative name is less than an rdata with only absolute names.
+ if our_relative:
+ return -1
+ else:
+ return 1
+ elif our_relative or their_relative:
+ raise NoRelativeRdataOrdering
+ if our == their:
+ return 0
+ elif our > their:
+ return 1
+ else:
+ return -1
+
+ def __eq__(self, other):
+ if not isinstance(other, Rdata):
+ return False
+ if self.rdclass != other.rdclass or self.rdtype != other.rdtype:
+ return False
+ our_relative = False
+ their_relative = False
+ try:
+ our = self.to_digestable()
+ except dns.name.NeedAbsoluteNameOrOrigin:
+ our = self.to_digestable(dns.name.root)
+ our_relative = True
+ try:
+ their = other.to_digestable()
+ except dns.name.NeedAbsoluteNameOrOrigin:
+ their = other.to_digestable(dns.name.root)
+ their_relative = True
+ if our_relative != their_relative:
+ return False
+ return our == their
+
+ def __ne__(self, other):
+ if not isinstance(other, Rdata):
+ return True
+ if self.rdclass != other.rdclass or self.rdtype != other.rdtype:
+ return True
+ return not self.__eq__(other)
+
+ def __lt__(self, other):
+ if (
+ not isinstance(other, Rdata)
+ or self.rdclass != other.rdclass
+ or self.rdtype != other.rdtype
+ ):
+ return NotImplemented
+ return self._cmp(other) < 0
+
+ def __le__(self, other):
+ if (
+ not isinstance(other, Rdata)
+ or self.rdclass != other.rdclass
+ or self.rdtype != other.rdtype
+ ):
+ return NotImplemented
+ return self._cmp(other) <= 0
+
+ def __ge__(self, other):
+ if (
+ not isinstance(other, Rdata)
+ or self.rdclass != other.rdclass
+ or self.rdtype != other.rdtype
+ ):
+ return NotImplemented
+ return self._cmp(other) >= 0
+
+ def __gt__(self, other):
+ if (
+ not isinstance(other, Rdata)
+ or self.rdclass != other.rdclass
+ or self.rdtype != other.rdtype
+ ):
+ return NotImplemented
+ return self._cmp(other) > 0
+
+ def __hash__(self):
+ return hash(self.to_digestable(dns.name.root))
+
+ @classmethod
+ def from_text(
+ cls,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ tok: dns.tokenizer.Tokenizer,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ relativize_to: Optional[dns.name.Name] = None,
+ ) -> "Rdata":
+ raise NotImplementedError # pragma: no cover
+
+ @classmethod
+ def from_wire_parser(
+ cls,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ parser: dns.wire.Parser,
+ origin: Optional[dns.name.Name] = None,
+ ) -> "Rdata":
+ raise NotImplementedError # pragma: no cover
+
+ def replace(self, **kwargs: Any) -> "Rdata":
+ """
+ Create a new Rdata instance based on the instance replace was
+ invoked on. It is possible to pass different parameters to
+ override the corresponding properties of the base Rdata.
+
+ Any field specific to the Rdata type can be replaced, but the
+ *rdtype* and *rdclass* fields cannot.
+
+ Returns an instance of the same Rdata subclass as *self*.
+ """
+
+ # Get the constructor parameters.
+ parameters = inspect.signature(self.__init__).parameters # type: ignore
+
+ # Ensure that all of the arguments correspond to valid fields.
+ # Don't allow rdclass or rdtype to be changed, though.
+ for key in kwargs:
+ if key == "rdcomment":
+ continue
+ if key not in parameters:
+ raise AttributeError(
+ "'{}' object has no attribute '{}'".format(
+ self.__class__.__name__, key
+ )
+ )
+ if key in ("rdclass", "rdtype"):
+ raise AttributeError(
+ "Cannot overwrite '{}' attribute '{}'".format(
+ self.__class__.__name__, key
+ )
+ )
+
+ # Construct the parameter list. For each field, use the value in
+ # kwargs if present, and the current value otherwise.
+ args = (kwargs.get(key, getattr(self, key)) for key in parameters)
+
+ # Create, validate, and return the new object.
+ rd = self.__class__(*args)
+ # The comment is not set in the constructor, so give it special
+ # handling.
+ rdcomment = kwargs.get("rdcomment", self.rdcomment)
+ if rdcomment is not None:
+ object.__setattr__(rd, "rdcomment", rdcomment)
+ return rd
+
+ # Type checking and conversion helpers. These are class methods as
+ # they don't touch object state and may be useful to others.
+
+ @classmethod
+ def _as_rdataclass(cls, value):
+ return dns.rdataclass.RdataClass.make(value)
+
+ @classmethod
+ def _as_rdatatype(cls, value):
+ return dns.rdatatype.RdataType.make(value)
+
+ @classmethod
+ def _as_bytes(
+ cls,
+ value: Any,
+ encode: bool = False,
+ max_length: Optional[int] = None,
+ empty_ok: bool = True,
+ ) -> bytes:
+ if encode and isinstance(value, str):
+ bvalue = value.encode()
+ elif isinstance(value, bytearray):
+ bvalue = bytes(value)
+ elif isinstance(value, bytes):
+ bvalue = value
+ else:
+ raise ValueError("not bytes")
+ if max_length is not None and len(bvalue) > max_length:
+ raise ValueError("too long")
+ if not empty_ok and len(bvalue) == 0:
+ raise ValueError("empty bytes not allowed")
+ return bvalue
+
+ @classmethod
+ def _as_name(cls, value):
+ # Note that proper name conversion (e.g. with origin and IDNA
+ # awareness) is expected to be done via from_text. This is just
+ # a simple thing for people invoking the constructor directly.
+ if isinstance(value, str):
+ return dns.name.from_text(value)
+ elif not isinstance(value, dns.name.Name):
+ raise ValueError("not a name")
+ return value
+
+ @classmethod
+ def _as_uint8(cls, value):
+ if not isinstance(value, int):
+ raise ValueError("not an integer")
+ if value < 0 or value > 255:
+ raise ValueError("not a uint8")
+ return value
+
+ @classmethod
+ def _as_uint16(cls, value):
+ if not isinstance(value, int):
+ raise ValueError("not an integer")
+ if value < 0 or value > 65535:
+ raise ValueError("not a uint16")
+ return value
+
+ @classmethod
+ def _as_uint32(cls, value):
+ if not isinstance(value, int):
+ raise ValueError("not an integer")
+ if value < 0 or value > 4294967295:
+ raise ValueError("not a uint32")
+ return value
+
+ @classmethod
+ def _as_uint48(cls, value):
+ if not isinstance(value, int):
+ raise ValueError("not an integer")
+ if value < 0 or value > 281474976710655:
+ raise ValueError("not a uint48")
+ return value
+
+ @classmethod
+ def _as_int(cls, value, low=None, high=None):
+ if not isinstance(value, int):
+ raise ValueError("not an integer")
+ if low is not None and value < low:
+ raise ValueError("value too small")
+ if high is not None and value > high:
+ raise ValueError("value too large")
+ return value
+
+ @classmethod
+ def _as_ipv4_address(cls, value):
+ if isinstance(value, str):
+ return dns.ipv4.canonicalize(value)
+ elif isinstance(value, bytes):
+ return dns.ipv4.inet_ntoa(value)
+ else:
+ raise ValueError("not an IPv4 address")
+
+ @classmethod
+ def _as_ipv6_address(cls, value):
+ if isinstance(value, str):
+ return dns.ipv6.canonicalize(value)
+ elif isinstance(value, bytes):
+ return dns.ipv6.inet_ntoa(value)
+ else:
+ raise ValueError("not an IPv6 address")
+
+ @classmethod
+ def _as_bool(cls, value):
+ if isinstance(value, bool):
+ return value
+ else:
+ raise ValueError("not a boolean")
+
+ @classmethod
+ def _as_ttl(cls, value):
+ if isinstance(value, int):
+ return cls._as_int(value, 0, dns.ttl.MAX_TTL)
+ elif isinstance(value, str):
+ return dns.ttl.from_text(value)
+ else:
+ raise ValueError("not a TTL")
+
+ @classmethod
+ def _as_tuple(cls, value, as_value):
+ try:
+ # For user convenience, if value is a singleton of the list
+ # element type, wrap it in a tuple.
+ return (as_value(value),)
+ except Exception:
+ # Otherwise, check each element of the iterable *value*
+ # against *as_value*.
+ return tuple(as_value(v) for v in value)
+
+ # Processing order
+
+ @classmethod
+ def _processing_order(cls, iterable):
+ items = list(iterable)
+ random.shuffle(items)
+ return items
+
+
+@dns.immutable.immutable
+class GenericRdata(Rdata):
+ """Generic Rdata Class
+
+ This class is used for rdata types for which we have no better
+ implementation. It implements the DNS "unknown RRs" scheme.
+ """
+
+ __slots__ = ["data"]
+
+ def __init__(self, rdclass, rdtype, data):
+ super().__init__(rdclass, rdtype)
+ self.data = data
+
+ def to_text(
+ self,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ **kw: Dict[str, Any],
+ ) -> str:
+ return r"\# %d " % len(self.data) + _hexify(self.data, **kw)
+
+ @classmethod
+ def from_text(
+ cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None
+ ):
+ token = tok.get()
+ if not token.is_identifier() or token.value != r"\#":
+ raise dns.exception.SyntaxError(r"generic rdata does not start with \#")
+ length = tok.get_int()
+ hex = tok.concatenate_remaining_identifiers(True).encode()
+ data = binascii.unhexlify(hex)
+ if len(data) != length:
+ raise dns.exception.SyntaxError("generic rdata hex data has wrong length")
+ return cls(rdclass, rdtype, data)
+
+ def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
+ file.write(self.data)
+
+ @classmethod
+ def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
+ return cls(rdclass, rdtype, parser.get_remaining())
+
+
+_rdata_classes: Dict[Tuple[dns.rdataclass.RdataClass, dns.rdatatype.RdataType], Any] = (
+ {}
+)
+_module_prefix = "dns.rdtypes"
+
+
+def get_rdata_class(rdclass, rdtype):
+ cls = _rdata_classes.get((rdclass, rdtype))
+ if not cls:
+ cls = _rdata_classes.get((dns.rdatatype.ANY, rdtype))
+ if not cls:
+ rdclass_text = dns.rdataclass.to_text(rdclass)
+ rdtype_text = dns.rdatatype.to_text(rdtype)
+ rdtype_text = rdtype_text.replace("-", "_")
+ try:
+ mod = import_module(
+ ".".join([_module_prefix, rdclass_text, rdtype_text])
+ )
+ cls = getattr(mod, rdtype_text)
+ _rdata_classes[(rdclass, rdtype)] = cls
+ except ImportError:
+ try:
+ mod = import_module(".".join([_module_prefix, "ANY", rdtype_text]))
+ cls = getattr(mod, rdtype_text)
+ _rdata_classes[(dns.rdataclass.ANY, rdtype)] = cls
+ _rdata_classes[(rdclass, rdtype)] = cls
+ except ImportError:
+ pass
+ if not cls:
+ cls = GenericRdata
+ _rdata_classes[(rdclass, rdtype)] = cls
+ return cls
+
+
+def from_text(
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ tok: Union[dns.tokenizer.Tokenizer, str],
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ relativize_to: Optional[dns.name.Name] = None,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+) -> Rdata:
+ """Build an rdata object from text format.
+
+ This function attempts to dynamically load a class which
+ implements the specified rdata class and type. If there is no
+ class-and-type-specific implementation, the GenericRdata class
+ is used.
+
+ Once a class is chosen, its from_text() class method is called
+ with the parameters to this function.
+
+ If *tok* is a ``str``, then a tokenizer is created and the string
+ is used as its input.
+
+ *rdclass*, a ``dns.rdataclass.RdataClass`` or ``str``, the rdataclass.
+
+ *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdatatype.
+
+ *tok*, a ``dns.tokenizer.Tokenizer`` or a ``str``.
+
+ *origin*, a ``dns.name.Name`` (or ``None``), the
+ origin to use for relative names.
+
+ *relativize*, a ``bool``. If true, name will be relativized.
+
+ *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
+ when relativizing names. If not set, the *origin* value will be used.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder to use if a tokenizer needs to be created. If
+ ``None``, the default IDNA 2003 encoder/decoder is used. If a
+ tokenizer is not created, then the codec associated with the tokenizer
+ is the one that is used.
+
+ Returns an instance of the chosen Rdata subclass.
+
+ """
+ if isinstance(tok, str):
+ tok = dns.tokenizer.Tokenizer(tok, idna_codec=idna_codec)
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ cls = get_rdata_class(rdclass, rdtype)
+ with dns.exception.ExceptionWrapper(dns.exception.SyntaxError):
+ rdata = None
+ if cls != GenericRdata:
+ # peek at first token
+ token = tok.get()
+ tok.unget(token)
+ if token.is_identifier() and token.value == r"\#":
+ #
+ # Known type using the generic syntax. Extract the
+ # wire form from the generic syntax, and then run
+ # from_wire on it.
+ #
+ grdata = GenericRdata.from_text(
+ rdclass, rdtype, tok, origin, relativize, relativize_to
+ )
+ rdata = from_wire(
+ rdclass, rdtype, grdata.data, 0, len(grdata.data), origin
+ )
+ #
+ # If this comparison isn't equal, then there must have been
+ # compressed names in the wire format, which is an error,
+ # there being no reasonable context to decompress with.
+ #
+ rwire = rdata.to_wire()
+ if rwire != grdata.data:
+ raise dns.exception.SyntaxError(
+ "compressed data in "
+ "generic syntax form "
+ "of known rdatatype"
+ )
+ if rdata is None:
+ rdata = cls.from_text(
+ rdclass, rdtype, tok, origin, relativize, relativize_to
+ )
+ token = tok.get_eol_as_token()
+ if token.comment is not None:
+ object.__setattr__(rdata, "rdcomment", token.comment)
+ return rdata
+
+
+def from_wire_parser(
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ parser: dns.wire.Parser,
+ origin: Optional[dns.name.Name] = None,
+) -> Rdata:
+ """Build an rdata object from wire format
+
+ This function attempts to dynamically load a class which
+ implements the specified rdata class and type. If there is no
+ class-and-type-specific implementation, the GenericRdata class
+ is used.
+
+ Once a class is chosen, its from_wire() class method is called
+ with the parameters to this function.
+
+ *rdclass*, a ``dns.rdataclass.RdataClass`` or ``str``, the rdataclass.
+
+ *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdatatype.
+
+ *parser*, a ``dns.wire.Parser``, the parser, which should be
+ restricted to the rdata length.
+
+ *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``,
+ then names will be relativized to this origin.
+
+ Returns an instance of the chosen Rdata subclass.
+ """
+
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ cls = get_rdata_class(rdclass, rdtype)
+ with dns.exception.ExceptionWrapper(dns.exception.FormError):
+ return cls.from_wire_parser(rdclass, rdtype, parser, origin)
+
+
+def from_wire(
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ wire: bytes,
+ current: int,
+ rdlen: int,
+ origin: Optional[dns.name.Name] = None,
+) -> Rdata:
+ """Build an rdata object from wire format
+
+ This function attempts to dynamically load a class which
+ implements the specified rdata class and type. If there is no
+ class-and-type-specific implementation, the GenericRdata class
+ is used.
+
+ Once a class is chosen, its from_wire() class method is called
+ with the parameters to this function.
+
+ *rdclass*, an ``int``, the rdataclass.
+
+ *rdtype*, an ``int``, the rdatatype.
+
+ *wire*, a ``bytes``, the wire-format message.
+
+ *current*, an ``int``, the offset in wire of the beginning of
+ the rdata.
+
+ *rdlen*, an ``int``, the length of the wire-format rdata
+
+ *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``,
+ then names will be relativized to this origin.
+
+ Returns an instance of the chosen Rdata subclass.
+ """
+ parser = dns.wire.Parser(wire, current)
+ with parser.restrict_to(rdlen):
+ return from_wire_parser(rdclass, rdtype, parser, origin)
+
+
+class RdatatypeExists(dns.exception.DNSException):
+ """DNS rdatatype already exists."""
+
+ supp_kwargs = {"rdclass", "rdtype"}
+ fmt = (
+ "The rdata type with class {rdclass:d} and rdtype {rdtype:d} "
+ + "already exists."
+ )
+
+
+def register_type(
+ implementation: Any,
+ rdtype: int,
+ rdtype_text: str,
+ is_singleton: bool = False,
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+) -> None:
+ """Dynamically register a module to handle an rdatatype.
+
+ *implementation*, a module implementing the type in the usual dnspython
+ way.
+
+ *rdtype*, an ``int``, the rdatatype to register.
+
+ *rdtype_text*, a ``str``, the textual form of the rdatatype.
+
+ *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e.
+ RRsets of the type can have only one member.)
+
+ *rdclass*, the rdataclass of the type, or ``dns.rdataclass.ANY`` if
+ it applies to all classes.
+ """
+
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ existing_cls = get_rdata_class(rdclass, rdtype)
+ if existing_cls != GenericRdata or dns.rdatatype.is_metatype(rdtype):
+ raise RdatatypeExists(rdclass=rdclass, rdtype=rdtype)
+ _rdata_classes[(rdclass, rdtype)] = getattr(
+ implementation, rdtype_text.replace("-", "_")
+ )
+ dns.rdatatype.register_type(rdtype, rdtype_text, is_singleton)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdataclass.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdataclass.py
new file mode 100644
index 0000000000000000000000000000000000000000..89b85a79c27ca8eb40bd85d65a17b6280fc50a43
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdataclass.py
@@ -0,0 +1,118 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Rdata Classes."""
+
+import dns.enum
+import dns.exception
+
+
+class RdataClass(dns.enum.IntEnum):
+ """DNS Rdata Class"""
+
+ RESERVED0 = 0
+ IN = 1
+ INTERNET = IN
+ CH = 3
+ CHAOS = CH
+ HS = 4
+ HESIOD = HS
+ NONE = 254
+ ANY = 255
+
+ @classmethod
+ def _maximum(cls):
+ return 65535
+
+ @classmethod
+ def _short_name(cls):
+ return "class"
+
+ @classmethod
+ def _prefix(cls):
+ return "CLASS"
+
+ @classmethod
+ def _unknown_exception_class(cls):
+ return UnknownRdataclass
+
+
+_metaclasses = {RdataClass.NONE, RdataClass.ANY}
+
+
+class UnknownRdataclass(dns.exception.DNSException):
+ """A DNS class is unknown."""
+
+
+def from_text(text: str) -> RdataClass:
+ """Convert text into a DNS rdata class value.
+
+ The input text can be a defined DNS RR class mnemonic or
+ instance of the DNS generic class syntax.
+
+ For example, "IN" and "CLASS1" will both result in a value of 1.
+
+ Raises ``dns.rdatatype.UnknownRdataclass`` if the class is unknown.
+
+ Raises ``ValueError`` if the rdata class value is not >= 0 and <= 65535.
+
+ Returns a ``dns.rdataclass.RdataClass``.
+ """
+
+ return RdataClass.from_text(text)
+
+
+def to_text(value: RdataClass) -> str:
+ """Convert a DNS rdata class value to text.
+
+ If the value has a known mnemonic, it will be used, otherwise the
+ DNS generic class syntax will be used.
+
+ Raises ``ValueError`` if the rdata class value is not >= 0 and <= 65535.
+
+ Returns a ``str``.
+ """
+
+ return RdataClass.to_text(value)
+
+
+def is_metaclass(rdclass: RdataClass) -> bool:
+ """True if the specified class is a metaclass.
+
+ The currently defined metaclasses are ANY and NONE.
+
+ *rdclass* is a ``dns.rdataclass.RdataClass``.
+ """
+
+ if rdclass in _metaclasses:
+ return True
+ return False
+
+
+### BEGIN generated RdataClass constants
+
+RESERVED0 = RdataClass.RESERVED0
+IN = RdataClass.IN
+INTERNET = RdataClass.INTERNET
+CH = RdataClass.CH
+CHAOS = RdataClass.CHAOS
+HS = RdataClass.HS
+HESIOD = RdataClass.HESIOD
+NONE = RdataClass.NONE
+ANY = RdataClass.ANY
+
+### END generated RdataClass constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdataset.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bff58d7a5afde491accad2e9ce6d04e86febc6f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdataset.py
@@ -0,0 +1,516 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS rdatasets (an rdataset is a set of rdatas of a given type and class)"""
+
+import io
+import random
+import struct
+from typing import Any, Collection, Dict, List, Optional, Union, cast
+
+import dns.exception
+import dns.immutable
+import dns.name
+import dns.rdata
+import dns.rdataclass
+import dns.rdatatype
+import dns.renderer
+import dns.set
+import dns.ttl
+
+# define SimpleSet here for backwards compatibility
+SimpleSet = dns.set.Set
+
+
+class DifferingCovers(dns.exception.DNSException):
+ """An attempt was made to add a DNS SIG/RRSIG whose covered type
+ is not the same as that of the other rdatas in the rdataset."""
+
+
+class IncompatibleTypes(dns.exception.DNSException):
+ """An attempt was made to add DNS RR data of an incompatible type."""
+
+
+class Rdataset(dns.set.Set):
+ """A DNS rdataset."""
+
+ __slots__ = ["rdclass", "rdtype", "covers", "ttl"]
+
+ def __init__(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ ttl: int = 0,
+ ):
+ """Create a new rdataset of the specified class and type.
+
+ *rdclass*, a ``dns.rdataclass.RdataClass``, the rdataclass.
+
+ *rdtype*, an ``dns.rdatatype.RdataType``, the rdatatype.
+
+ *covers*, an ``dns.rdatatype.RdataType``, the covered rdatatype.
+
+ *ttl*, an ``int``, the TTL.
+ """
+
+ super().__init__()
+ self.rdclass = rdclass
+ self.rdtype: dns.rdatatype.RdataType = rdtype
+ self.covers: dns.rdatatype.RdataType = covers
+ self.ttl = ttl
+
+ def _clone(self):
+ obj = super()._clone()
+ obj.rdclass = self.rdclass
+ obj.rdtype = self.rdtype
+ obj.covers = self.covers
+ obj.ttl = self.ttl
+ return obj
+
+ def update_ttl(self, ttl: int) -> None:
+ """Perform TTL minimization.
+
+ Set the TTL of the rdataset to be the lesser of the set's current
+ TTL or the specified TTL. If the set contains no rdatas, set the TTL
+ to the specified TTL.
+
+ *ttl*, an ``int`` or ``str``.
+ """
+ ttl = dns.ttl.make(ttl)
+ if len(self) == 0:
+ self.ttl = ttl
+ elif ttl < self.ttl:
+ self.ttl = ttl
+
+ def add( # pylint: disable=arguments-differ,arguments-renamed
+ self, rd: dns.rdata.Rdata, ttl: Optional[int] = None
+ ) -> None:
+ """Add the specified rdata to the rdataset.
+
+ If the optional *ttl* parameter is supplied, then
+ ``self.update_ttl(ttl)`` will be called prior to adding the rdata.
+
+ *rd*, a ``dns.rdata.Rdata``, the rdata
+
+ *ttl*, an ``int``, the TTL.
+
+ Raises ``dns.rdataset.IncompatibleTypes`` if the type and class
+ do not match the type and class of the rdataset.
+
+ Raises ``dns.rdataset.DifferingCovers`` if the type is a signature
+ type and the covered type does not match that of the rdataset.
+ """
+
+ #
+ # If we're adding a signature, do some special handling to
+ # check that the signature covers the same type as the
+ # other rdatas in this rdataset. If this is the first rdata
+ # in the set, initialize the covers field.
+ #
+ if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype:
+ raise IncompatibleTypes
+ if ttl is not None:
+ self.update_ttl(ttl)
+ if self.rdtype == dns.rdatatype.RRSIG or self.rdtype == dns.rdatatype.SIG:
+ covers = rd.covers()
+ if len(self) == 0 and self.covers == dns.rdatatype.NONE:
+ self.covers = covers
+ elif self.covers != covers:
+ raise DifferingCovers
+ if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0:
+ self.clear()
+ super().add(rd)
+
+ def union_update(self, other):
+ self.update_ttl(other.ttl)
+ super().union_update(other)
+
+ def intersection_update(self, other):
+ self.update_ttl(other.ttl)
+ super().intersection_update(other)
+
+ def update(self, other):
+ """Add all rdatas in other to self.
+
+ *other*, a ``dns.rdataset.Rdataset``, the rdataset from which
+ to update.
+ """
+
+ self.update_ttl(other.ttl)
+ super().update(other)
+
+ def _rdata_repr(self):
+ def maybe_truncate(s):
+ if len(s) > 100:
+ return s[:100] + "..."
+ return s
+
+ return "[%s]" % ", ".join("<%s>" % maybe_truncate(str(rr)) for rr in self)
+
+ def __repr__(self):
+ if self.covers == 0:
+ ctext = ""
+ else:
+ ctext = "(" + dns.rdatatype.to_text(self.covers) + ")"
+ return (
+ ""
+ )
+
+ def __str__(self):
+ return self.to_text()
+
+ def __eq__(self, other):
+ if not isinstance(other, Rdataset):
+ return False
+ if (
+ self.rdclass != other.rdclass
+ or self.rdtype != other.rdtype
+ or self.covers != other.covers
+ ):
+ return False
+ return super().__eq__(other)
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def to_text(
+ self,
+ name: Optional[dns.name.Name] = None,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ override_rdclass: Optional[dns.rdataclass.RdataClass] = None,
+ want_comments: bool = False,
+ **kw: Dict[str, Any],
+ ) -> str:
+ """Convert the rdataset into DNS zone file format.
+
+ See ``dns.name.Name.choose_relativity`` for more information
+ on how *origin* and *relativize* determine the way names
+ are emitted.
+
+ Any additional keyword arguments are passed on to the rdata
+ ``to_text()`` method.
+
+ *name*, a ``dns.name.Name``. If name is not ``None``, emit RRs with
+ *name* as the owner name.
+
+ *origin*, a ``dns.name.Name`` or ``None``, the origin for relative
+ names.
+
+ *relativize*, a ``bool``. If ``True``, names will be relativized
+ to *origin*.
+
+ *override_rdclass*, a ``dns.rdataclass.RdataClass`` or ``None``.
+ If not ``None``, use this class instead of the Rdataset's class.
+
+ *want_comments*, a ``bool``. If ``True``, emit comments for rdata
+ which have them. The default is ``False``.
+ """
+
+ if name is not None:
+ name = name.choose_relativity(origin, relativize)
+ ntext = str(name)
+ pad = " "
+ else:
+ ntext = ""
+ pad = ""
+ s = io.StringIO()
+ if override_rdclass is not None:
+ rdclass = override_rdclass
+ else:
+ rdclass = self.rdclass
+ if len(self) == 0:
+ #
+ # Empty rdatasets are used for the question section, and in
+ # some dynamic updates, so we don't need to print out the TTL
+ # (which is meaningless anyway).
+ #
+ s.write(
+ "{}{}{} {}\n".format(
+ ntext,
+ pad,
+ dns.rdataclass.to_text(rdclass),
+ dns.rdatatype.to_text(self.rdtype),
+ )
+ )
+ else:
+ for rd in self:
+ extra = ""
+ if want_comments:
+ if rd.rdcomment:
+ extra = f" ;{rd.rdcomment}"
+ s.write(
+ "%s%s%d %s %s %s%s\n"
+ % (
+ ntext,
+ pad,
+ self.ttl,
+ dns.rdataclass.to_text(rdclass),
+ dns.rdatatype.to_text(self.rdtype),
+ rd.to_text(origin=origin, relativize=relativize, **kw),
+ extra,
+ )
+ )
+ #
+ # We strip off the final \n for the caller's convenience in printing
+ #
+ return s.getvalue()[:-1]
+
+ def to_wire(
+ self,
+ name: dns.name.Name,
+ file: Any,
+ compress: Optional[dns.name.CompressType] = None,
+ origin: Optional[dns.name.Name] = None,
+ override_rdclass: Optional[dns.rdataclass.RdataClass] = None,
+ want_shuffle: bool = True,
+ ) -> int:
+ """Convert the rdataset to wire format.
+
+ *name*, a ``dns.name.Name`` is the owner name to use.
+
+ *file* is the file where the name is emitted (typically a
+ BytesIO file).
+
+ *compress*, a ``dict``, is the compression table to use. If
+ ``None`` (the default), names will not be compressed.
+
+ *origin* is a ``dns.name.Name`` or ``None``. If the name is
+ relative and origin is not ``None``, then *origin* will be appended
+ to it.
+
+ *override_rdclass*, an ``int``, is used as the class instead of the
+ class of the rdataset. This is useful when rendering rdatasets
+ associated with dynamic updates.
+
+ *want_shuffle*, a ``bool``. If ``True``, then the order of the
+ Rdatas within the Rdataset will be shuffled before rendering.
+
+ Returns an ``int``, the number of records emitted.
+ """
+
+ if override_rdclass is not None:
+ rdclass = override_rdclass
+ want_shuffle = False
+ else:
+ rdclass = self.rdclass
+ if len(self) == 0:
+ name.to_wire(file, compress, origin)
+ file.write(struct.pack("!HHIH", self.rdtype, rdclass, 0, 0))
+ return 1
+ else:
+ l: Union[Rdataset, List[dns.rdata.Rdata]]
+ if want_shuffle:
+ l = list(self)
+ random.shuffle(l)
+ else:
+ l = self
+ for rd in l:
+ name.to_wire(file, compress, origin)
+ file.write(struct.pack("!HHI", self.rdtype, rdclass, self.ttl))
+ with dns.renderer.prefixed_length(file, 2):
+ rd.to_wire(file, compress, origin)
+ return len(self)
+
+ def match(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType,
+ ) -> bool:
+ """Returns ``True`` if this rdataset matches the specified class,
+ type, and covers.
+ """
+ if self.rdclass == rdclass and self.rdtype == rdtype and self.covers == covers:
+ return True
+ return False
+
+ def processing_order(self) -> List[dns.rdata.Rdata]:
+ """Return rdatas in a valid processing order according to the type's
+ specification. For example, MX records are in preference order from
+ lowest to highest preferences, with items of the same preference
+ shuffled.
+
+ For types that do not define a processing order, the rdatas are
+ simply shuffled.
+ """
+ if len(self) == 0:
+ return []
+ else:
+ return self[0]._processing_order(iter(self))
+
+
+@dns.immutable.immutable
+class ImmutableRdataset(Rdataset): # lgtm[py/missing-equals]
+ """An immutable DNS rdataset."""
+
+ _clone_class = Rdataset
+
+ def __init__(self, rdataset: Rdataset):
+ """Create an immutable rdataset from the specified rdataset."""
+
+ super().__init__(
+ rdataset.rdclass, rdataset.rdtype, rdataset.covers, rdataset.ttl
+ )
+ self.items = dns.immutable.Dict(rdataset.items)
+
+ def update_ttl(self, ttl):
+ raise TypeError("immutable")
+
+ def add(self, rd, ttl=None):
+ raise TypeError("immutable")
+
+ def union_update(self, other):
+ raise TypeError("immutable")
+
+ def intersection_update(self, other):
+ raise TypeError("immutable")
+
+ def update(self, other):
+ raise TypeError("immutable")
+
+ def __delitem__(self, i):
+ raise TypeError("immutable")
+
+ # lgtm complains about these not raising ArithmeticError, but there is
+ # precedent for overrides of these methods in other classes to raise
+ # TypeError, and it seems like the better exception.
+
+ def __ior__(self, other): # lgtm[py/unexpected-raise-in-special-method]
+ raise TypeError("immutable")
+
+ def __iand__(self, other): # lgtm[py/unexpected-raise-in-special-method]
+ raise TypeError("immutable")
+
+ def __iadd__(self, other): # lgtm[py/unexpected-raise-in-special-method]
+ raise TypeError("immutable")
+
+ def __isub__(self, other): # lgtm[py/unexpected-raise-in-special-method]
+ raise TypeError("immutable")
+
+ def clear(self):
+ raise TypeError("immutable")
+
+ def __copy__(self):
+ return ImmutableRdataset(super().copy())
+
+ def copy(self):
+ return ImmutableRdataset(super().copy())
+
+ def union(self, other):
+ return ImmutableRdataset(super().union(other))
+
+ def intersection(self, other):
+ return ImmutableRdataset(super().intersection(other))
+
+ def difference(self, other):
+ return ImmutableRdataset(super().difference(other))
+
+ def symmetric_difference(self, other):
+ return ImmutableRdataset(super().symmetric_difference(other))
+
+
+def from_text_list(
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ ttl: int,
+ text_rdatas: Collection[str],
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ relativize_to: Optional[dns.name.Name] = None,
+) -> Rdataset:
+ """Create an rdataset with the specified class, type, and TTL, and with
+ the specified list of rdatas in text format.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder to use; if ``None``, the default IDNA 2003
+ encoder/decoder is used.
+
+ *origin*, a ``dns.name.Name`` (or ``None``), the
+ origin to use for relative names.
+
+ *relativize*, a ``bool``. If true, name will be relativized.
+
+ *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
+ when relativizing names. If not set, the *origin* value will be used.
+
+ Returns a ``dns.rdataset.Rdataset`` object.
+ """
+
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ r = Rdataset(rdclass, rdtype)
+ r.update_ttl(ttl)
+ for t in text_rdatas:
+ rd = dns.rdata.from_text(
+ r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec
+ )
+ r.add(rd)
+ return r
+
+
+def from_text(
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ ttl: int,
+ *text_rdatas: Any,
+) -> Rdataset:
+ """Create an rdataset with the specified class, type, and TTL, and with
+ the specified rdatas in text format.
+
+ Returns a ``dns.rdataset.Rdataset`` object.
+ """
+
+ return from_text_list(rdclass, rdtype, ttl, cast(Collection[str], text_rdatas))
+
+
+def from_rdata_list(ttl: int, rdatas: Collection[dns.rdata.Rdata]) -> Rdataset:
+ """Create an rdataset with the specified TTL, and with
+ the specified list of rdata objects.
+
+ Returns a ``dns.rdataset.Rdataset`` object.
+ """
+
+ if len(rdatas) == 0:
+ raise ValueError("rdata list must not be empty")
+ r = None
+ for rd in rdatas:
+ if r is None:
+ r = Rdataset(rd.rdclass, rd.rdtype)
+ r.update_ttl(ttl)
+ r.add(rd)
+ assert r is not None
+ return r
+
+
+def from_rdata(ttl: int, *rdatas: Any) -> Rdataset:
+ """Create an rdataset with the specified TTL, and with
+ the specified rdata objects.
+
+ Returns a ``dns.rdataset.Rdataset`` object.
+ """
+
+ return from_rdata_list(ttl, cast(Collection[dns.rdata.Rdata], rdatas))
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdatatype.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdatatype.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6c581867bcc7cd7e806ea92c3dab28f0d021d3e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rdatatype.py
@@ -0,0 +1,332 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Rdata Types."""
+
+from typing import Dict
+
+import dns.enum
+import dns.exception
+
+
+class RdataType(dns.enum.IntEnum):
+ """DNS Rdata Type"""
+
+ TYPE0 = 0
+ NONE = 0
+ A = 1
+ NS = 2
+ MD = 3
+ MF = 4
+ CNAME = 5
+ SOA = 6
+ MB = 7
+ MG = 8
+ MR = 9
+ NULL = 10
+ WKS = 11
+ PTR = 12
+ HINFO = 13
+ MINFO = 14
+ MX = 15
+ TXT = 16
+ RP = 17
+ AFSDB = 18
+ X25 = 19
+ ISDN = 20
+ RT = 21
+ NSAP = 22
+ NSAP_PTR = 23
+ SIG = 24
+ KEY = 25
+ PX = 26
+ GPOS = 27
+ AAAA = 28
+ LOC = 29
+ NXT = 30
+ SRV = 33
+ NAPTR = 35
+ KX = 36
+ CERT = 37
+ A6 = 38
+ DNAME = 39
+ OPT = 41
+ APL = 42
+ DS = 43
+ SSHFP = 44
+ IPSECKEY = 45
+ RRSIG = 46
+ NSEC = 47
+ DNSKEY = 48
+ DHCID = 49
+ NSEC3 = 50
+ NSEC3PARAM = 51
+ TLSA = 52
+ SMIMEA = 53
+ HIP = 55
+ NINFO = 56
+ CDS = 59
+ CDNSKEY = 60
+ OPENPGPKEY = 61
+ CSYNC = 62
+ ZONEMD = 63
+ SVCB = 64
+ HTTPS = 65
+ SPF = 99
+ UNSPEC = 103
+ NID = 104
+ L32 = 105
+ L64 = 106
+ LP = 107
+ EUI48 = 108
+ EUI64 = 109
+ TKEY = 249
+ TSIG = 250
+ IXFR = 251
+ AXFR = 252
+ MAILB = 253
+ MAILA = 254
+ ANY = 255
+ URI = 256
+ CAA = 257
+ AVC = 258
+ AMTRELAY = 260
+ TA = 32768
+ DLV = 32769
+
+ @classmethod
+ def _maximum(cls):
+ return 65535
+
+ @classmethod
+ def _short_name(cls):
+ return "type"
+
+ @classmethod
+ def _prefix(cls):
+ return "TYPE"
+
+ @classmethod
+ def _extra_from_text(cls, text):
+ if text.find("-") >= 0:
+ try:
+ return cls[text.replace("-", "_")]
+ except KeyError:
+ pass
+ return _registered_by_text.get(text)
+
+ @classmethod
+ def _extra_to_text(cls, value, current_text):
+ if current_text is None:
+ return _registered_by_value.get(value)
+ if current_text.find("_") >= 0:
+ return current_text.replace("_", "-")
+ return current_text
+
+ @classmethod
+ def _unknown_exception_class(cls):
+ return UnknownRdatatype
+
+
+_registered_by_text: Dict[str, RdataType] = {}
+_registered_by_value: Dict[RdataType, str] = {}
+
+_metatypes = {RdataType.OPT}
+
+_singletons = {
+ RdataType.SOA,
+ RdataType.NXT,
+ RdataType.DNAME,
+ RdataType.NSEC,
+ RdataType.CNAME,
+}
+
+
+class UnknownRdatatype(dns.exception.DNSException):
+ """DNS resource record type is unknown."""
+
+
+def from_text(text: str) -> RdataType:
+ """Convert text into a DNS rdata type value.
+
+ The input text can be a defined DNS RR type mnemonic or
+ instance of the DNS generic type syntax.
+
+ For example, "NS" and "TYPE2" will both result in a value of 2.
+
+ Raises ``dns.rdatatype.UnknownRdatatype`` if the type is unknown.
+
+ Raises ``ValueError`` if the rdata type value is not >= 0 and <= 65535.
+
+ Returns a ``dns.rdatatype.RdataType``.
+ """
+
+ return RdataType.from_text(text)
+
+
+def to_text(value: RdataType) -> str:
+ """Convert a DNS rdata type value to text.
+
+ If the value has a known mnemonic, it will be used, otherwise the
+ DNS generic type syntax will be used.
+
+ Raises ``ValueError`` if the rdata type value is not >= 0 and <= 65535.
+
+ Returns a ``str``.
+ """
+
+ return RdataType.to_text(value)
+
+
+def is_metatype(rdtype: RdataType) -> bool:
+ """True if the specified type is a metatype.
+
+ *rdtype* is a ``dns.rdatatype.RdataType``.
+
+ The currently defined metatypes are TKEY, TSIG, IXFR, AXFR, MAILA,
+ MAILB, ANY, and OPT.
+
+ Returns a ``bool``.
+ """
+
+ return (256 > rdtype >= 128) or rdtype in _metatypes
+
+
+def is_singleton(rdtype: RdataType) -> bool:
+ """Is the specified type a singleton type?
+
+ Singleton types can only have a single rdata in an rdataset, or a single
+ RR in an RRset.
+
+ The currently defined singleton types are CNAME, DNAME, NSEC, NXT, and
+ SOA.
+
+ *rdtype* is an ``int``.
+
+ Returns a ``bool``.
+ """
+
+ if rdtype in _singletons:
+ return True
+ return False
+
+
+# pylint: disable=redefined-outer-name
+def register_type(
+ rdtype: RdataType, rdtype_text: str, is_singleton: bool = False
+) -> None:
+ """Dynamically register an rdatatype.
+
+ *rdtype*, a ``dns.rdatatype.RdataType``, the rdatatype to register.
+
+ *rdtype_text*, a ``str``, the textual form of the rdatatype.
+
+ *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e.
+ RRsets of the type can have only one member.)
+ """
+
+ _registered_by_text[rdtype_text] = rdtype
+ _registered_by_value[rdtype] = rdtype_text
+ if is_singleton:
+ _singletons.add(rdtype)
+
+
+### BEGIN generated RdataType constants
+
+TYPE0 = RdataType.TYPE0
+NONE = RdataType.NONE
+A = RdataType.A
+NS = RdataType.NS
+MD = RdataType.MD
+MF = RdataType.MF
+CNAME = RdataType.CNAME
+SOA = RdataType.SOA
+MB = RdataType.MB
+MG = RdataType.MG
+MR = RdataType.MR
+NULL = RdataType.NULL
+WKS = RdataType.WKS
+PTR = RdataType.PTR
+HINFO = RdataType.HINFO
+MINFO = RdataType.MINFO
+MX = RdataType.MX
+TXT = RdataType.TXT
+RP = RdataType.RP
+AFSDB = RdataType.AFSDB
+X25 = RdataType.X25
+ISDN = RdataType.ISDN
+RT = RdataType.RT
+NSAP = RdataType.NSAP
+NSAP_PTR = RdataType.NSAP_PTR
+SIG = RdataType.SIG
+KEY = RdataType.KEY
+PX = RdataType.PX
+GPOS = RdataType.GPOS
+AAAA = RdataType.AAAA
+LOC = RdataType.LOC
+NXT = RdataType.NXT
+SRV = RdataType.SRV
+NAPTR = RdataType.NAPTR
+KX = RdataType.KX
+CERT = RdataType.CERT
+A6 = RdataType.A6
+DNAME = RdataType.DNAME
+OPT = RdataType.OPT
+APL = RdataType.APL
+DS = RdataType.DS
+SSHFP = RdataType.SSHFP
+IPSECKEY = RdataType.IPSECKEY
+RRSIG = RdataType.RRSIG
+NSEC = RdataType.NSEC
+DNSKEY = RdataType.DNSKEY
+DHCID = RdataType.DHCID
+NSEC3 = RdataType.NSEC3
+NSEC3PARAM = RdataType.NSEC3PARAM
+TLSA = RdataType.TLSA
+SMIMEA = RdataType.SMIMEA
+HIP = RdataType.HIP
+NINFO = RdataType.NINFO
+CDS = RdataType.CDS
+CDNSKEY = RdataType.CDNSKEY
+OPENPGPKEY = RdataType.OPENPGPKEY
+CSYNC = RdataType.CSYNC
+ZONEMD = RdataType.ZONEMD
+SVCB = RdataType.SVCB
+HTTPS = RdataType.HTTPS
+SPF = RdataType.SPF
+UNSPEC = RdataType.UNSPEC
+NID = RdataType.NID
+L32 = RdataType.L32
+L64 = RdataType.L64
+LP = RdataType.LP
+EUI48 = RdataType.EUI48
+EUI64 = RdataType.EUI64
+TKEY = RdataType.TKEY
+TSIG = RdataType.TSIG
+IXFR = RdataType.IXFR
+AXFR = RdataType.AXFR
+MAILB = RdataType.MAILB
+MAILA = RdataType.MAILA
+ANY = RdataType.ANY
+URI = RdataType.URI
+CAA = RdataType.CAA
+AVC = RdataType.AVC
+AMTRELAY = RdataType.AMTRELAY
+TA = RdataType.TA
+DLV = RdataType.DLV
+
+### END generated RdataType constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/renderer.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/renderer.py
new file mode 100644
index 0000000000000000000000000000000000000000..a77481f67c8cdab5205ce8453550eb6f02ec566c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/renderer.py
@@ -0,0 +1,346 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Help for building DNS wire format messages"""
+
+import contextlib
+import io
+import random
+import struct
+import time
+
+import dns.exception
+import dns.tsig
+
+QUESTION = 0
+ANSWER = 1
+AUTHORITY = 2
+ADDITIONAL = 3
+
+
+@contextlib.contextmanager
+def prefixed_length(output, length_length):
+ output.write(b"\00" * length_length)
+ start = output.tell()
+ yield
+ end = output.tell()
+ length = end - start
+ if length > 0:
+ try:
+ output.seek(start - length_length)
+ try:
+ output.write(length.to_bytes(length_length, "big"))
+ except OverflowError:
+ raise dns.exception.FormError
+ finally:
+ output.seek(end)
+
+
+class Renderer:
+ """Helper class for building DNS wire-format messages.
+
+ Most applications can use the higher-level L{dns.message.Message}
+ class and its to_wire() method to generate wire-format messages.
+ This class is for those applications which need finer control
+ over the generation of messages.
+
+ Typical use::
+
+ r = dns.renderer.Renderer(id=1, flags=0x80, max_size=512)
+ r.add_question(qname, qtype, qclass)
+ r.add_rrset(dns.renderer.ANSWER, rrset_1)
+ r.add_rrset(dns.renderer.ANSWER, rrset_2)
+ r.add_rrset(dns.renderer.AUTHORITY, ns_rrset)
+ r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_1)
+ r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_2)
+ r.add_edns(0, 0, 4096)
+ r.write_header()
+ r.add_tsig(keyname, secret, 300, 1, 0, '', request_mac)
+ wire = r.get_wire()
+
+ If padding is going to be used, then the OPT record MUST be
+ written after everything else in the additional section except for
+ the TSIG (if any).
+
+ output, an io.BytesIO, where rendering is written
+
+ id: the message id
+
+ flags: the message flags
+
+ max_size: the maximum size of the message
+
+ origin: the origin to use when rendering relative names
+
+ compress: the compression table
+
+ section: an int, the section currently being rendered
+
+ counts: list of the number of RRs in each section
+
+ mac: the MAC of the rendered message (if TSIG was used)
+ """
+
+ def __init__(self, id=None, flags=0, max_size=65535, origin=None):
+ """Initialize a new renderer."""
+
+ self.output = io.BytesIO()
+ if id is None:
+ self.id = random.randint(0, 65535)
+ else:
+ self.id = id
+ self.flags = flags
+ self.max_size = max_size
+ self.origin = origin
+ self.compress = {}
+ self.section = QUESTION
+ self.counts = [0, 0, 0, 0]
+ self.output.write(b"\x00" * 12)
+ self.mac = ""
+ self.reserved = 0
+ self.was_padded = False
+
+ def _rollback(self, where):
+ """Truncate the output buffer at offset *where*, and remove any
+ compression table entries that pointed beyond the truncation
+ point.
+ """
+
+ self.output.seek(where)
+ self.output.truncate()
+ keys_to_delete = []
+ for k, v in self.compress.items():
+ if v >= where:
+ keys_to_delete.append(k)
+ for k in keys_to_delete:
+ del self.compress[k]
+
+ def _set_section(self, section):
+ """Set the renderer's current section.
+
+ Sections must be rendered order: QUESTION, ANSWER, AUTHORITY,
+ ADDITIONAL. Sections may be empty.
+
+ Raises dns.exception.FormError if an attempt was made to set
+ a section value less than the current section.
+ """
+
+ if self.section != section:
+ if self.section > section:
+ raise dns.exception.FormError
+ self.section = section
+
+ @contextlib.contextmanager
+ def _track_size(self):
+ start = self.output.tell()
+ yield start
+ if self.output.tell() > self.max_size:
+ self._rollback(start)
+ raise dns.exception.TooBig
+
+ @contextlib.contextmanager
+ def _temporarily_seek_to(self, where):
+ current = self.output.tell()
+ try:
+ self.output.seek(where)
+ yield
+ finally:
+ self.output.seek(current)
+
+ def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN):
+ """Add a question to the message."""
+
+ self._set_section(QUESTION)
+ with self._track_size():
+ qname.to_wire(self.output, self.compress, self.origin)
+ self.output.write(struct.pack("!HH", rdtype, rdclass))
+ self.counts[QUESTION] += 1
+
+ def add_rrset(self, section, rrset, **kw):
+ """Add the rrset to the specified section.
+
+ Any keyword arguments are passed on to the rdataset's to_wire()
+ routine.
+ """
+
+ self._set_section(section)
+ with self._track_size():
+ n = rrset.to_wire(self.output, self.compress, self.origin, **kw)
+ self.counts[section] += n
+
+ def add_rdataset(self, section, name, rdataset, **kw):
+ """Add the rdataset to the specified section, using the specified
+ name as the owner name.
+
+ Any keyword arguments are passed on to the rdataset's to_wire()
+ routine.
+ """
+
+ self._set_section(section)
+ with self._track_size():
+ n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw)
+ self.counts[section] += n
+
+ def add_opt(self, opt, pad=0, opt_size=0, tsig_size=0):
+ """Add *opt* to the additional section, applying padding if desired. The
+ padding will take the specified precomputed OPT size and TSIG size into
+ account.
+
+ Note that we don't have reliable way of knowing how big a GSS-TSIG digest
+ might be, so we we might not get an even multiple of the pad in that case."""
+ if pad:
+ ttl = opt.ttl
+ assert opt_size >= 11
+ opt_rdata = opt[0]
+ size_without_padding = self.output.tell() + opt_size + tsig_size
+ remainder = size_without_padding % pad
+ if remainder:
+ pad = b"\x00" * (pad - remainder)
+ else:
+ pad = b""
+ options = list(opt_rdata.options)
+ options.append(dns.edns.GenericOption(dns.edns.OptionType.PADDING, pad))
+ opt = dns.message.Message._make_opt(ttl, opt_rdata.rdclass, options)
+ self.was_padded = True
+ self.add_rrset(ADDITIONAL, opt)
+
+ def add_edns(self, edns, ednsflags, payload, options=None):
+ """Add an EDNS OPT record to the message."""
+
+ # make sure the EDNS version in ednsflags agrees with edns
+ ednsflags &= 0xFF00FFFF
+ ednsflags |= edns << 16
+ opt = dns.message.Message._make_opt(ednsflags, payload, options)
+ self.add_opt(opt)
+
+ def add_tsig(
+ self,
+ keyname,
+ secret,
+ fudge,
+ id,
+ tsig_error,
+ other_data,
+ request_mac,
+ algorithm=dns.tsig.default_algorithm,
+ ):
+ """Add a TSIG signature to the message."""
+
+ s = self.output.getvalue()
+
+ if isinstance(secret, dns.tsig.Key):
+ key = secret
+ else:
+ key = dns.tsig.Key(keyname, secret, algorithm)
+ tsig = dns.message.Message._make_tsig(
+ keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data
+ )
+ (tsig, _) = dns.tsig.sign(s, key, tsig[0], int(time.time()), request_mac)
+ self._write_tsig(tsig, keyname)
+
+ def add_multi_tsig(
+ self,
+ ctx,
+ keyname,
+ secret,
+ fudge,
+ id,
+ tsig_error,
+ other_data,
+ request_mac,
+ algorithm=dns.tsig.default_algorithm,
+ ):
+ """Add a TSIG signature to the message. Unlike add_tsig(), this can be
+ used for a series of consecutive DNS envelopes, e.g. for a zone
+ transfer over TCP [RFC2845, 4.4].
+
+ For the first message in the sequence, give ctx=None. For each
+ subsequent message, give the ctx that was returned from the
+ add_multi_tsig() call for the previous message."""
+
+ s = self.output.getvalue()
+
+ if isinstance(secret, dns.tsig.Key):
+ key = secret
+ else:
+ key = dns.tsig.Key(keyname, secret, algorithm)
+ tsig = dns.message.Message._make_tsig(
+ keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data
+ )
+ (tsig, ctx) = dns.tsig.sign(
+ s, key, tsig[0], int(time.time()), request_mac, ctx, True
+ )
+ self._write_tsig(tsig, keyname)
+ return ctx
+
+ def _write_tsig(self, tsig, keyname):
+ if self.was_padded:
+ compress = None
+ else:
+ compress = self.compress
+ self._set_section(ADDITIONAL)
+ with self._track_size():
+ keyname.to_wire(self.output, compress, self.origin)
+ self.output.write(
+ struct.pack("!HHI", dns.rdatatype.TSIG, dns.rdataclass.ANY, 0)
+ )
+ with prefixed_length(self.output, 2):
+ tsig.to_wire(self.output)
+
+ self.counts[ADDITIONAL] += 1
+ with self._temporarily_seek_to(10):
+ self.output.write(struct.pack("!H", self.counts[ADDITIONAL]))
+
+ def write_header(self):
+ """Write the DNS message header.
+
+ Writing the DNS message header is done after all sections
+ have been rendered, but before the optional TSIG signature
+ is added.
+ """
+
+ with self._temporarily_seek_to(0):
+ self.output.write(
+ struct.pack(
+ "!HHHHHH",
+ self.id,
+ self.flags,
+ self.counts[0],
+ self.counts[1],
+ self.counts[2],
+ self.counts[3],
+ )
+ )
+
+ def get_wire(self):
+ """Return the wire format message."""
+
+ return self.output.getvalue()
+
+ def reserve(self, size: int) -> None:
+ """Reserve *size* bytes."""
+ if size < 0:
+ raise ValueError("reserved amount must be non-negative")
+ if size > self.max_size:
+ raise ValueError("cannot reserve more than the maximum size")
+ self.reserved += size
+ self.max_size -= size
+
+ def release_reserved(self) -> None:
+ """Release the reserved bytes."""
+ self.max_size += self.reserved
+ self.reserved = 0
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/resolver.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..f08f824d0e587d0e8ce4a3e89a0df87221e3f44f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/resolver.py
@@ -0,0 +1,2054 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS stub resolver."""
+
+import contextlib
+import random
+import socket
+import sys
+import threading
+import time
+import warnings
+from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union
+from urllib.parse import urlparse
+
+import dns._ddr
+import dns.edns
+import dns.exception
+import dns.flags
+import dns.inet
+import dns.ipv4
+import dns.ipv6
+import dns.message
+import dns.name
+import dns.nameserver
+import dns.query
+import dns.rcode
+import dns.rdataclass
+import dns.rdatatype
+import dns.rdtypes.svcbbase
+import dns.reversename
+import dns.tsig
+
+if sys.platform == "win32":
+ import dns.win32util
+
+
+class NXDOMAIN(dns.exception.DNSException):
+ """The DNS query name does not exist."""
+
+ supp_kwargs = {"qnames", "responses"}
+ fmt = None # we have our own __str__ implementation
+
+ # pylint: disable=arguments-differ
+
+ # We do this as otherwise mypy complains about unexpected keyword argument
+ # idna_exception
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def _check_kwargs(self, qnames, responses=None):
+ if not isinstance(qnames, (list, tuple, set)):
+ raise AttributeError("qnames must be a list, tuple or set")
+ if len(qnames) == 0:
+ raise AttributeError("qnames must contain at least one element")
+ if responses is None:
+ responses = {}
+ elif not isinstance(responses, dict):
+ raise AttributeError("responses must be a dict(qname=response)")
+ kwargs = dict(qnames=qnames, responses=responses)
+ return kwargs
+
+ def __str__(self) -> str:
+ if "qnames" not in self.kwargs:
+ return super().__str__()
+ qnames = self.kwargs["qnames"]
+ if len(qnames) > 1:
+ msg = "None of DNS query names exist"
+ else:
+ msg = "The DNS query name does not exist"
+ qnames = ", ".join(map(str, qnames))
+ return "{}: {}".format(msg, qnames)
+
+ @property
+ def canonical_name(self):
+ """Return the unresolved canonical name."""
+ if "qnames" not in self.kwargs:
+ raise TypeError("parametrized exception required")
+ for qname in self.kwargs["qnames"]:
+ response = self.kwargs["responses"][qname]
+ try:
+ cname = response.canonical_name()
+ if cname != qname:
+ return cname
+ except Exception:
+ # We can just eat this exception as it means there was
+ # something wrong with the response.
+ pass
+ return self.kwargs["qnames"][0]
+
+ def __add__(self, e_nx):
+ """Augment by results from another NXDOMAIN exception."""
+ qnames0 = list(self.kwargs.get("qnames", []))
+ responses0 = dict(self.kwargs.get("responses", {}))
+ responses1 = e_nx.kwargs.get("responses", {})
+ for qname1 in e_nx.kwargs.get("qnames", []):
+ if qname1 not in qnames0:
+ qnames0.append(qname1)
+ if qname1 in responses1:
+ responses0[qname1] = responses1[qname1]
+ return NXDOMAIN(qnames=qnames0, responses=responses0)
+
+ def qnames(self):
+ """All of the names that were tried.
+
+ Returns a list of ``dns.name.Name``.
+ """
+ return self.kwargs["qnames"]
+
+ def responses(self):
+ """A map from queried names to their NXDOMAIN responses.
+
+ Returns a dict mapping a ``dns.name.Name`` to a
+ ``dns.message.Message``.
+ """
+ return self.kwargs["responses"]
+
+ def response(self, qname):
+ """The response for query *qname*.
+
+ Returns a ``dns.message.Message``.
+ """
+ return self.kwargs["responses"][qname]
+
+
+class YXDOMAIN(dns.exception.DNSException):
+ """The DNS query name is too long after DNAME substitution."""
+
+
+ErrorTuple = Tuple[
+ Optional[str],
+ bool,
+ int,
+ Union[Exception, str],
+ Optional[dns.message.Message],
+]
+
+
+def _errors_to_text(errors: List[ErrorTuple]) -> List[str]:
+ """Turn a resolution errors trace into a list of text."""
+ texts = []
+ for err in errors:
+ texts.append("Server {} answered {}".format(err[0], err[3]))
+ return texts
+
+
+class LifetimeTimeout(dns.exception.Timeout):
+ """The resolution lifetime expired."""
+
+ msg = "The resolution lifetime expired."
+ fmt = "%s after {timeout:.3f} seconds: {errors}" % msg[:-1]
+ supp_kwargs = {"timeout", "errors"}
+
+ # We do this as otherwise mypy complains about unexpected keyword argument
+ # idna_exception
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def _fmt_kwargs(self, **kwargs):
+ srv_msgs = _errors_to_text(kwargs["errors"])
+ return super()._fmt_kwargs(
+ timeout=kwargs["timeout"], errors="; ".join(srv_msgs)
+ )
+
+
+# We added more detail to resolution timeouts, but they are still
+# subclasses of dns.exception.Timeout for backwards compatibility. We also
+# keep dns.resolver.Timeout defined for backwards compatibility.
+Timeout = LifetimeTimeout
+
+
+class NoAnswer(dns.exception.DNSException):
+ """The DNS response does not contain an answer to the question."""
+
+ fmt = "The DNS response does not contain an answer to the question: {query}"
+ supp_kwargs = {"response"}
+
+ # We do this as otherwise mypy complains about unexpected keyword argument
+ # idna_exception
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def _fmt_kwargs(self, **kwargs):
+ return super()._fmt_kwargs(query=kwargs["response"].question)
+
+ def response(self):
+ return self.kwargs["response"]
+
+
+class NoNameservers(dns.exception.DNSException):
+ """All nameservers failed to answer the query.
+
+ errors: list of servers and respective errors
+ The type of errors is
+ [(server IP address, any object convertible to string)].
+ Non-empty errors list will add explanatory message ()
+ """
+
+ msg = "All nameservers failed to answer the query."
+ fmt = "%s {query}: {errors}" % msg[:-1]
+ supp_kwargs = {"request", "errors"}
+
+ # We do this as otherwise mypy complains about unexpected keyword argument
+ # idna_exception
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def _fmt_kwargs(self, **kwargs):
+ srv_msgs = _errors_to_text(kwargs["errors"])
+ return super()._fmt_kwargs(
+ query=kwargs["request"].question, errors="; ".join(srv_msgs)
+ )
+
+
+class NotAbsolute(dns.exception.DNSException):
+ """An absolute domain name is required but a relative name was provided."""
+
+
+class NoRootSOA(dns.exception.DNSException):
+ """There is no SOA RR at the DNS root name. This should never happen!"""
+
+
+class NoMetaqueries(dns.exception.DNSException):
+ """DNS metaqueries are not allowed."""
+
+
+class NoResolverConfiguration(dns.exception.DNSException):
+ """Resolver configuration could not be read or specified no nameservers."""
+
+
+class Answer:
+ """DNS stub resolver answer.
+
+ Instances of this class bundle up the result of a successful DNS
+ resolution.
+
+ For convenience, the answer object implements much of the sequence
+ protocol, forwarding to its ``rrset`` attribute. E.g.
+ ``for a in answer`` is equivalent to ``for a in answer.rrset``.
+ ``answer[i]`` is equivalent to ``answer.rrset[i]``, and
+ ``answer[i:j]`` is equivalent to ``answer.rrset[i:j]``.
+
+ Note that CNAMEs or DNAMEs in the response may mean that answer
+ RRset's name might not be the query name.
+ """
+
+ def __init__(
+ self,
+ qname: dns.name.Name,
+ rdtype: dns.rdatatype.RdataType,
+ rdclass: dns.rdataclass.RdataClass,
+ response: dns.message.QueryMessage,
+ nameserver: Optional[str] = None,
+ port: Optional[int] = None,
+ ) -> None:
+ self.qname = qname
+ self.rdtype = rdtype
+ self.rdclass = rdclass
+ self.response = response
+ self.nameserver = nameserver
+ self.port = port
+ self.chaining_result = response.resolve_chaining()
+ # Copy some attributes out of chaining_result for backwards
+ # compatibility and convenience.
+ self.canonical_name = self.chaining_result.canonical_name
+ self.rrset = self.chaining_result.answer
+ self.expiration = time.time() + self.chaining_result.minimum_ttl
+
+ def __getattr__(self, attr): # pragma: no cover
+ if attr == "name":
+ return self.rrset.name
+ elif attr == "ttl":
+ return self.rrset.ttl
+ elif attr == "covers":
+ return self.rrset.covers
+ elif attr == "rdclass":
+ return self.rrset.rdclass
+ elif attr == "rdtype":
+ return self.rrset.rdtype
+ else:
+ raise AttributeError(attr)
+
+ def __len__(self) -> int:
+ return self.rrset and len(self.rrset) or 0
+
+ def __iter__(self):
+ return self.rrset and iter(self.rrset) or iter(tuple())
+
+ def __getitem__(self, i):
+ if self.rrset is None:
+ raise IndexError
+ return self.rrset[i]
+
+ def __delitem__(self, i):
+ if self.rrset is None:
+ raise IndexError
+ del self.rrset[i]
+
+
+class Answers(dict):
+ """A dict of DNS stub resolver answers, indexed by type."""
+
+
+class HostAnswers(Answers):
+ """A dict of DNS stub resolver answers to a host name lookup, indexed by
+ type.
+ """
+
+ @classmethod
+ def make(
+ cls,
+ v6: Optional[Answer] = None,
+ v4: Optional[Answer] = None,
+ add_empty: bool = True,
+ ) -> "HostAnswers":
+ answers = HostAnswers()
+ if v6 is not None and (add_empty or v6.rrset):
+ answers[dns.rdatatype.AAAA] = v6
+ if v4 is not None and (add_empty or v4.rrset):
+ answers[dns.rdatatype.A] = v4
+ return answers
+
+ # Returns pairs of (address, family) from this result, potentiallys
+ # filtering by address family.
+ def addresses_and_families(
+ self, family: int = socket.AF_UNSPEC
+ ) -> Iterator[Tuple[str, int]]:
+ if family == socket.AF_UNSPEC:
+ yield from self.addresses_and_families(socket.AF_INET6)
+ yield from self.addresses_and_families(socket.AF_INET)
+ return
+ elif family == socket.AF_INET6:
+ answer = self.get(dns.rdatatype.AAAA)
+ elif family == socket.AF_INET:
+ answer = self.get(dns.rdatatype.A)
+ else:
+ raise NotImplementedError(f"unknown address family {family}")
+ if answer:
+ for rdata in answer:
+ yield (rdata.address, family)
+
+ # Returns addresses from this result, potentially filtering by
+ # address family.
+ def addresses(self, family: int = socket.AF_UNSPEC) -> Iterator[str]:
+ return (pair[0] for pair in self.addresses_and_families(family))
+
+ # Returns the canonical name from this result.
+ def canonical_name(self) -> dns.name.Name:
+ answer = self.get(dns.rdatatype.AAAA, self.get(dns.rdatatype.A))
+ return answer.canonical_name
+
+
+class CacheStatistics:
+ """Cache Statistics"""
+
+ def __init__(self, hits: int = 0, misses: int = 0) -> None:
+ self.hits = hits
+ self.misses = misses
+
+ def reset(self) -> None:
+ self.hits = 0
+ self.misses = 0
+
+ def clone(self) -> "CacheStatistics":
+ return CacheStatistics(self.hits, self.misses)
+
+
+class CacheBase:
+ def __init__(self) -> None:
+ self.lock = threading.Lock()
+ self.statistics = CacheStatistics()
+
+ def reset_statistics(self) -> None:
+ """Reset all statistics to zero."""
+ with self.lock:
+ self.statistics.reset()
+
+ def hits(self) -> int:
+ """How many hits has the cache had?"""
+ with self.lock:
+ return self.statistics.hits
+
+ def misses(self) -> int:
+ """How many misses has the cache had?"""
+ with self.lock:
+ return self.statistics.misses
+
+ def get_statistics_snapshot(self) -> CacheStatistics:
+ """Return a consistent snapshot of all the statistics.
+
+ If running with multiple threads, it's better to take a
+ snapshot than to call statistics methods such as hits() and
+ misses() individually.
+ """
+ with self.lock:
+ return self.statistics.clone()
+
+
+CacheKey = Tuple[dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass]
+
+
+class Cache(CacheBase):
+ """Simple thread-safe DNS answer cache."""
+
+ def __init__(self, cleaning_interval: float = 300.0) -> None:
+ """*cleaning_interval*, a ``float`` is the number of seconds between
+ periodic cleanings.
+ """
+
+ super().__init__()
+ self.data: Dict[CacheKey, Answer] = {}
+ self.cleaning_interval = cleaning_interval
+ self.next_cleaning: float = time.time() + self.cleaning_interval
+
+ def _maybe_clean(self) -> None:
+ """Clean the cache if it's time to do so."""
+
+ now = time.time()
+ if self.next_cleaning <= now:
+ keys_to_delete = []
+ for k, v in self.data.items():
+ if v.expiration <= now:
+ keys_to_delete.append(k)
+ for k in keys_to_delete:
+ del self.data[k]
+ now = time.time()
+ self.next_cleaning = now + self.cleaning_interval
+
+ def get(self, key: CacheKey) -> Optional[Answer]:
+ """Get the answer associated with *key*.
+
+ Returns None if no answer is cached for the key.
+
+ *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)``
+ tuple whose values are the query name, rdtype, and rdclass respectively.
+
+ Returns a ``dns.resolver.Answer`` or ``None``.
+ """
+
+ with self.lock:
+ self._maybe_clean()
+ v = self.data.get(key)
+ if v is None or v.expiration <= time.time():
+ self.statistics.misses += 1
+ return None
+ self.statistics.hits += 1
+ return v
+
+ def put(self, key: CacheKey, value: Answer) -> None:
+ """Associate key and value in the cache.
+
+ *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)``
+ tuple whose values are the query name, rdtype, and rdclass respectively.
+
+ *value*, a ``dns.resolver.Answer``, the answer.
+ """
+
+ with self.lock:
+ self._maybe_clean()
+ self.data[key] = value
+
+ def flush(self, key: Optional[CacheKey] = None) -> None:
+ """Flush the cache.
+
+ If *key* is not ``None``, only that item is flushed. Otherwise the entire cache
+ is flushed.
+
+ *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)``
+ tuple whose values are the query name, rdtype, and rdclass respectively.
+ """
+
+ with self.lock:
+ if key is not None:
+ if key in self.data:
+ del self.data[key]
+ else:
+ self.data = {}
+ self.next_cleaning = time.time() + self.cleaning_interval
+
+
+class LRUCacheNode:
+ """LRUCache node."""
+
+ def __init__(self, key, value):
+ self.key = key
+ self.value = value
+ self.hits = 0
+ self.prev = self
+ self.next = self
+
+ def link_after(self, node: "LRUCacheNode") -> None:
+ self.prev = node
+ self.next = node.next
+ node.next.prev = self
+ node.next = self
+
+ def unlink(self) -> None:
+ self.next.prev = self.prev
+ self.prev.next = self.next
+
+
+class LRUCache(CacheBase):
+ """Thread-safe, bounded, least-recently-used DNS answer cache.
+
+ This cache is better than the simple cache (above) if you're
+ running a web crawler or other process that does a lot of
+ resolutions. The LRUCache has a maximum number of nodes, and when
+ it is full, the least-recently used node is removed to make space
+ for a new one.
+ """
+
+ def __init__(self, max_size: int = 100000) -> None:
+ """*max_size*, an ``int``, is the maximum number of nodes to cache;
+ it must be greater than 0.
+ """
+
+ super().__init__()
+ self.data: Dict[CacheKey, LRUCacheNode] = {}
+ self.set_max_size(max_size)
+ self.sentinel: LRUCacheNode = LRUCacheNode(None, None)
+ self.sentinel.prev = self.sentinel
+ self.sentinel.next = self.sentinel
+
+ def set_max_size(self, max_size: int) -> None:
+ if max_size < 1:
+ max_size = 1
+ self.max_size = max_size
+
+ def get(self, key: CacheKey) -> Optional[Answer]:
+ """Get the answer associated with *key*.
+
+ Returns None if no answer is cached for the key.
+
+ *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)``
+ tuple whose values are the query name, rdtype, and rdclass respectively.
+
+ Returns a ``dns.resolver.Answer`` or ``None``.
+ """
+
+ with self.lock:
+ node = self.data.get(key)
+ if node is None:
+ self.statistics.misses += 1
+ return None
+ # Unlink because we're either going to move the node to the front
+ # of the LRU list or we're going to free it.
+ node.unlink()
+ if node.value.expiration <= time.time():
+ del self.data[node.key]
+ self.statistics.misses += 1
+ return None
+ node.link_after(self.sentinel)
+ self.statistics.hits += 1
+ node.hits += 1
+ return node.value
+
+ def get_hits_for_key(self, key: CacheKey) -> int:
+ """Return the number of cache hits associated with the specified key."""
+ with self.lock:
+ node = self.data.get(key)
+ if node is None or node.value.expiration <= time.time():
+ return 0
+ else:
+ return node.hits
+
+ def put(self, key: CacheKey, value: Answer) -> None:
+ """Associate key and value in the cache.
+
+ *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)``
+ tuple whose values are the query name, rdtype, and rdclass respectively.
+
+ *value*, a ``dns.resolver.Answer``, the answer.
+ """
+
+ with self.lock:
+ node = self.data.get(key)
+ if node is not None:
+ node.unlink()
+ del self.data[node.key]
+ while len(self.data) >= self.max_size:
+ gnode = self.sentinel.prev
+ gnode.unlink()
+ del self.data[gnode.key]
+ node = LRUCacheNode(key, value)
+ node.link_after(self.sentinel)
+ self.data[key] = node
+
+ def flush(self, key: Optional[CacheKey] = None) -> None:
+ """Flush the cache.
+
+ If *key* is not ``None``, only that item is flushed. Otherwise the entire cache
+ is flushed.
+
+ *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)``
+ tuple whose values are the query name, rdtype, and rdclass respectively.
+ """
+
+ with self.lock:
+ if key is not None:
+ node = self.data.get(key)
+ if node is not None:
+ node.unlink()
+ del self.data[node.key]
+ else:
+ gnode = self.sentinel.next
+ while gnode != self.sentinel:
+ next = gnode.next
+ gnode.unlink()
+ gnode = next
+ self.data = {}
+
+
+class _Resolution:
+ """Helper class for dns.resolver.Resolver.resolve().
+
+ All of the "business logic" of resolution is encapsulated in this
+ class, allowing us to have multiple resolve() implementations
+ using different I/O schemes without copying all of the
+ complicated logic.
+
+ This class is a "friend" to dns.resolver.Resolver and manipulates
+ resolver data structures directly.
+ """
+
+ def __init__(
+ self,
+ resolver: "BaseResolver",
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ tcp: bool,
+ raise_on_no_answer: bool,
+ search: Optional[bool],
+ ) -> None:
+ if isinstance(qname, str):
+ qname = dns.name.from_text(qname, None)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ if dns.rdatatype.is_metatype(rdtype):
+ raise NoMetaqueries
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ if dns.rdataclass.is_metaclass(rdclass):
+ raise NoMetaqueries
+ self.resolver = resolver
+ self.qnames_to_try = resolver._get_qnames_to_try(qname, search)
+ self.qnames = self.qnames_to_try[:]
+ self.rdtype = rdtype
+ self.rdclass = rdclass
+ self.tcp = tcp
+ self.raise_on_no_answer = raise_on_no_answer
+ self.nxdomain_responses: Dict[dns.name.Name, dns.message.QueryMessage] = {}
+ # Initialize other things to help analysis tools
+ self.qname = dns.name.empty
+ self.nameservers: List[dns.nameserver.Nameserver] = []
+ self.current_nameservers: List[dns.nameserver.Nameserver] = []
+ self.errors: List[ErrorTuple] = []
+ self.nameserver: Optional[dns.nameserver.Nameserver] = None
+ self.tcp_attempt = False
+ self.retry_with_tcp = False
+ self.request: Optional[dns.message.QueryMessage] = None
+ self.backoff = 0.0
+
+ def next_request(
+ self,
+ ) -> Tuple[Optional[dns.message.QueryMessage], Optional[Answer]]:
+ """Get the next request to send, and check the cache.
+
+ Returns a (request, answer) tuple. At most one of request or
+ answer will not be None.
+ """
+
+ # We return a tuple instead of Union[Message,Answer] as it lets
+ # the caller avoid isinstance().
+
+ while len(self.qnames) > 0:
+ self.qname = self.qnames.pop(0)
+
+ # Do we know the answer?
+ if self.resolver.cache:
+ answer = self.resolver.cache.get(
+ (self.qname, self.rdtype, self.rdclass)
+ )
+ if answer is not None:
+ if answer.rrset is None and self.raise_on_no_answer:
+ raise NoAnswer(response=answer.response)
+ else:
+ return (None, answer)
+ answer = self.resolver.cache.get(
+ (self.qname, dns.rdatatype.ANY, self.rdclass)
+ )
+ if answer is not None and answer.response.rcode() == dns.rcode.NXDOMAIN:
+ # cached NXDOMAIN; record it and continue to next
+ # name.
+ self.nxdomain_responses[self.qname] = answer.response
+ continue
+
+ # Build the request
+ request = dns.message.make_query(self.qname, self.rdtype, self.rdclass)
+ if self.resolver.keyname is not None:
+ request.use_tsig(
+ self.resolver.keyring,
+ self.resolver.keyname,
+ algorithm=self.resolver.keyalgorithm,
+ )
+ request.use_edns(
+ self.resolver.edns,
+ self.resolver.ednsflags,
+ self.resolver.payload,
+ options=self.resolver.ednsoptions,
+ )
+ if self.resolver.flags is not None:
+ request.flags = self.resolver.flags
+
+ self.nameservers = self.resolver._enrich_nameservers(
+ self.resolver._nameservers,
+ self.resolver.nameserver_ports,
+ self.resolver.port,
+ )
+ if self.resolver.rotate:
+ random.shuffle(self.nameservers)
+ self.current_nameservers = self.nameservers[:]
+ self.errors = []
+ self.nameserver = None
+ self.tcp_attempt = False
+ self.retry_with_tcp = False
+ self.request = request
+ self.backoff = 0.10
+
+ return (request, None)
+
+ #
+ # We've tried everything and only gotten NXDOMAINs. (We know
+ # it's only NXDOMAINs as anything else would have returned
+ # before now.)
+ #
+ raise NXDOMAIN(qnames=self.qnames_to_try, responses=self.nxdomain_responses)
+
+ def next_nameserver(self) -> Tuple[dns.nameserver.Nameserver, bool, float]:
+ if self.retry_with_tcp:
+ assert self.nameserver is not None
+ assert not self.nameserver.is_always_max_size()
+ self.tcp_attempt = True
+ self.retry_with_tcp = False
+ return (self.nameserver, True, 0)
+
+ backoff = 0.0
+ if not self.current_nameservers:
+ if len(self.nameservers) == 0:
+ # Out of things to try!
+ raise NoNameservers(request=self.request, errors=self.errors)
+ self.current_nameservers = self.nameservers[:]
+ backoff = self.backoff
+ self.backoff = min(self.backoff * 2, 2)
+
+ self.nameserver = self.current_nameservers.pop(0)
+ self.tcp_attempt = self.tcp or self.nameserver.is_always_max_size()
+ return (self.nameserver, self.tcp_attempt, backoff)
+
+ def query_result(
+ self, response: Optional[dns.message.Message], ex: Optional[Exception]
+ ) -> Tuple[Optional[Answer], bool]:
+ #
+ # returns an (answer: Answer, end_loop: bool) tuple.
+ #
+ assert self.nameserver is not None
+ if ex:
+ # Exception during I/O or from_wire()
+ assert response is None
+ self.errors.append(
+ (
+ str(self.nameserver),
+ self.tcp_attempt,
+ self.nameserver.answer_port(),
+ ex,
+ response,
+ )
+ )
+ if (
+ isinstance(ex, dns.exception.FormError)
+ or isinstance(ex, EOFError)
+ or isinstance(ex, OSError)
+ or isinstance(ex, NotImplementedError)
+ ):
+ # This nameserver is no good, take it out of the mix.
+ self.nameservers.remove(self.nameserver)
+ elif isinstance(ex, dns.message.Truncated):
+ if self.tcp_attempt:
+ # Truncation with TCP is no good!
+ self.nameservers.remove(self.nameserver)
+ else:
+ self.retry_with_tcp = True
+ return (None, False)
+ # We got an answer!
+ assert response is not None
+ assert isinstance(response, dns.message.QueryMessage)
+ rcode = response.rcode()
+ if rcode == dns.rcode.NOERROR:
+ try:
+ answer = Answer(
+ self.qname,
+ self.rdtype,
+ self.rdclass,
+ response,
+ self.nameserver.answer_nameserver(),
+ self.nameserver.answer_port(),
+ )
+ except Exception as e:
+ self.errors.append(
+ (
+ str(self.nameserver),
+ self.tcp_attempt,
+ self.nameserver.answer_port(),
+ e,
+ response,
+ )
+ )
+ # The nameserver is no good, take it out of the mix.
+ self.nameservers.remove(self.nameserver)
+ return (None, False)
+ if self.resolver.cache:
+ self.resolver.cache.put((self.qname, self.rdtype, self.rdclass), answer)
+ if answer.rrset is None and self.raise_on_no_answer:
+ raise NoAnswer(response=answer.response)
+ return (answer, True)
+ elif rcode == dns.rcode.NXDOMAIN:
+ # Further validate the response by making an Answer, even
+ # if we aren't going to cache it.
+ try:
+ answer = Answer(
+ self.qname, dns.rdatatype.ANY, dns.rdataclass.IN, response
+ )
+ except Exception as e:
+ self.errors.append(
+ (
+ str(self.nameserver),
+ self.tcp_attempt,
+ self.nameserver.answer_port(),
+ e,
+ response,
+ )
+ )
+ # The nameserver is no good, take it out of the mix.
+ self.nameservers.remove(self.nameserver)
+ return (None, False)
+ self.nxdomain_responses[self.qname] = response
+ if self.resolver.cache:
+ self.resolver.cache.put(
+ (self.qname, dns.rdatatype.ANY, self.rdclass), answer
+ )
+ # Make next_nameserver() return None, so caller breaks its
+ # inner loop and calls next_request().
+ return (None, True)
+ elif rcode == dns.rcode.YXDOMAIN:
+ yex = YXDOMAIN()
+ self.errors.append(
+ (
+ str(self.nameserver),
+ self.tcp_attempt,
+ self.nameserver.answer_port(),
+ yex,
+ response,
+ )
+ )
+ raise yex
+ else:
+ #
+ # We got a response, but we're not happy with the
+ # rcode in it.
+ #
+ if rcode != dns.rcode.SERVFAIL or not self.resolver.retry_servfail:
+ self.nameservers.remove(self.nameserver)
+ self.errors.append(
+ (
+ str(self.nameserver),
+ self.tcp_attempt,
+ self.nameserver.answer_port(),
+ dns.rcode.to_text(rcode),
+ response,
+ )
+ )
+ return (None, False)
+
+
+class BaseResolver:
+ """DNS stub resolver."""
+
+ # We initialize in reset()
+ #
+ # pylint: disable=attribute-defined-outside-init
+
+ domain: dns.name.Name
+ nameserver_ports: Dict[str, int]
+ port: int
+ search: List[dns.name.Name]
+ use_search_by_default: bool
+ timeout: float
+ lifetime: float
+ keyring: Optional[Any]
+ keyname: Optional[Union[dns.name.Name, str]]
+ keyalgorithm: Union[dns.name.Name, str]
+ edns: int
+ ednsflags: int
+ ednsoptions: Optional[List[dns.edns.Option]]
+ payload: int
+ cache: Any
+ flags: Optional[int]
+ retry_servfail: bool
+ rotate: bool
+ ndots: Optional[int]
+ _nameservers: Sequence[Union[str, dns.nameserver.Nameserver]]
+
+ def __init__(
+ self, filename: str = "/etc/resolv.conf", configure: bool = True
+ ) -> None:
+ """*filename*, a ``str`` or file object, specifying a file
+ in standard /etc/resolv.conf format. This parameter is meaningful
+ only when *configure* is true and the platform is POSIX.
+
+ *configure*, a ``bool``. If True (the default), the resolver
+ instance is configured in the normal fashion for the operating
+ system the resolver is running on. (I.e. by reading a
+ /etc/resolv.conf file on POSIX systems and from the registry
+ on Windows systems.)
+ """
+
+ self.reset()
+ if configure:
+ if sys.platform == "win32":
+ self.read_registry()
+ elif filename:
+ self.read_resolv_conf(filename)
+
+ def reset(self) -> None:
+ """Reset all resolver configuration to the defaults."""
+
+ self.domain = dns.name.Name(dns.name.from_text(socket.gethostname())[1:])
+ if len(self.domain) == 0:
+ self.domain = dns.name.root
+ self._nameservers = []
+ self.nameserver_ports = {}
+ self.port = 53
+ self.search = []
+ self.use_search_by_default = False
+ self.timeout = 2.0
+ self.lifetime = 5.0
+ self.keyring = None
+ self.keyname = None
+ self.keyalgorithm = dns.tsig.default_algorithm
+ self.edns = -1
+ self.ednsflags = 0
+ self.ednsoptions = None
+ self.payload = 0
+ self.cache = None
+ self.flags = None
+ self.retry_servfail = False
+ self.rotate = False
+ self.ndots = None
+
+ def read_resolv_conf(self, f: Any) -> None:
+ """Process *f* as a file in the /etc/resolv.conf format. If f is
+ a ``str``, it is used as the name of the file to open; otherwise it
+ is treated as the file itself.
+
+ Interprets the following items:
+
+ - nameserver - name server IP address
+
+ - domain - local domain name
+
+ - search - search list for host-name lookup
+
+ - options - supported options are rotate, timeout, edns0, and ndots
+
+ """
+
+ nameservers = []
+ if isinstance(f, str):
+ try:
+ cm: contextlib.AbstractContextManager = open(f)
+ except OSError:
+ # /etc/resolv.conf doesn't exist, can't be read, etc.
+ raise NoResolverConfiguration(f"cannot open {f}")
+ else:
+ cm = contextlib.nullcontext(f)
+ with cm as f:
+ for l in f:
+ if len(l) == 0 or l[0] == "#" or l[0] == ";":
+ continue
+ tokens = l.split()
+
+ # Any line containing less than 2 tokens is malformed
+ if len(tokens) < 2:
+ continue
+
+ if tokens[0] == "nameserver":
+ nameservers.append(tokens[1])
+ elif tokens[0] == "domain":
+ self.domain = dns.name.from_text(tokens[1])
+ # domain and search are exclusive
+ self.search = []
+ elif tokens[0] == "search":
+ # the last search wins
+ self.search = []
+ for suffix in tokens[1:]:
+ self.search.append(dns.name.from_text(suffix))
+ # We don't set domain as it is not used if
+ # len(self.search) > 0
+ elif tokens[0] == "options":
+ for opt in tokens[1:]:
+ if opt == "rotate":
+ self.rotate = True
+ elif opt == "edns0":
+ self.use_edns()
+ elif "timeout" in opt:
+ try:
+ self.timeout = int(opt.split(":")[1])
+ except (ValueError, IndexError):
+ pass
+ elif "ndots" in opt:
+ try:
+ self.ndots = int(opt.split(":")[1])
+ except (ValueError, IndexError):
+ pass
+ if len(nameservers) == 0:
+ raise NoResolverConfiguration("no nameservers")
+ # Assigning directly instead of appending means we invoke the
+ # setter logic, with additonal checking and enrichment.
+ self.nameservers = nameservers
+
+ def read_registry(self) -> None:
+ """Extract resolver configuration from the Windows registry."""
+ try:
+ info = dns.win32util.get_dns_info() # type: ignore
+ if info.domain is not None:
+ self.domain = info.domain
+ self.nameservers = info.nameservers
+ self.search = info.search
+ except AttributeError:
+ raise NotImplementedError
+
+ def _compute_timeout(
+ self,
+ start: float,
+ lifetime: Optional[float] = None,
+ errors: Optional[List[ErrorTuple]] = None,
+ ) -> float:
+ lifetime = self.lifetime if lifetime is None else lifetime
+ now = time.time()
+ duration = now - start
+ if errors is None:
+ errors = []
+ if duration < 0:
+ if duration < -1:
+ # Time going backwards is bad. Just give up.
+ raise LifetimeTimeout(timeout=duration, errors=errors)
+ else:
+ # Time went backwards, but only a little. This can
+ # happen, e.g. under vmware with older linux kernels.
+ # Pretend it didn't happen.
+ duration = 0
+ if duration >= lifetime:
+ raise LifetimeTimeout(timeout=duration, errors=errors)
+ return min(lifetime - duration, self.timeout)
+
+ def _get_qnames_to_try(
+ self, qname: dns.name.Name, search: Optional[bool]
+ ) -> List[dns.name.Name]:
+ # This is a separate method so we can unit test the search
+ # rules without requiring the Internet.
+ if search is None:
+ search = self.use_search_by_default
+ qnames_to_try = []
+ if qname.is_absolute():
+ qnames_to_try.append(qname)
+ else:
+ abs_qname = qname.concatenate(dns.name.root)
+ if search:
+ if len(self.search) > 0:
+ # There is a search list, so use it exclusively
+ search_list = self.search[:]
+ elif self.domain != dns.name.root and self.domain is not None:
+ # We have some notion of a domain that isn't the root, so
+ # use it as the search list.
+ search_list = [self.domain]
+ else:
+ search_list = []
+ # Figure out the effective ndots (default is 1)
+ if self.ndots is None:
+ ndots = 1
+ else:
+ ndots = self.ndots
+ for suffix in search_list:
+ qnames_to_try.append(qname + suffix)
+ if len(qname) > ndots:
+ # The name has at least ndots dots, so we should try an
+ # absolute query first.
+ qnames_to_try.insert(0, abs_qname)
+ else:
+ # The name has less than ndots dots, so we should search
+ # first, then try the absolute name.
+ qnames_to_try.append(abs_qname)
+ else:
+ qnames_to_try.append(abs_qname)
+ return qnames_to_try
+
+ def use_tsig(
+ self,
+ keyring: Any,
+ keyname: Optional[Union[dns.name.Name, str]] = None,
+ algorithm: Union[dns.name.Name, str] = dns.tsig.default_algorithm,
+ ) -> None:
+ """Add a TSIG signature to each query.
+
+ The parameters are passed to ``dns.message.Message.use_tsig()``;
+ see its documentation for details.
+ """
+
+ self.keyring = keyring
+ self.keyname = keyname
+ self.keyalgorithm = algorithm
+
+ def use_edns(
+ self,
+ edns: Optional[Union[int, bool]] = 0,
+ ednsflags: int = 0,
+ payload: int = dns.message.DEFAULT_EDNS_PAYLOAD,
+ options: Optional[List[dns.edns.Option]] = None,
+ ) -> None:
+ """Configure EDNS behavior.
+
+ *edns*, an ``int``, is the EDNS level to use. Specifying
+ ``None``, ``False``, or ``-1`` means "do not use EDNS", and in this case
+ the other parameters are ignored. Specifying ``True`` is
+ equivalent to specifying 0, i.e. "use EDNS0".
+
+ *ednsflags*, an ``int``, the EDNS flag values.
+
+ *payload*, an ``int``, is the EDNS sender's payload field, which is the
+ maximum size of UDP datagram the sender can handle. I.e. how big
+ a response to this message can be.
+
+ *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS
+ options.
+ """
+
+ if edns is None or edns is False:
+ edns = -1
+ elif edns is True:
+ edns = 0
+ self.edns = edns
+ self.ednsflags = ednsflags
+ self.payload = payload
+ self.ednsoptions = options
+
+ def set_flags(self, flags: int) -> None:
+ """Overrides the default flags with your own.
+
+ *flags*, an ``int``, the message flags to use.
+ """
+
+ self.flags = flags
+
+ @classmethod
+ def _enrich_nameservers(
+ cls,
+ nameservers: Sequence[Union[str, dns.nameserver.Nameserver]],
+ nameserver_ports: Dict[str, int],
+ default_port: int,
+ ) -> List[dns.nameserver.Nameserver]:
+ enriched_nameservers = []
+ if isinstance(nameservers, list):
+ for nameserver in nameservers:
+ enriched_nameserver: dns.nameserver.Nameserver
+ if isinstance(nameserver, dns.nameserver.Nameserver):
+ enriched_nameserver = nameserver
+ elif dns.inet.is_address(nameserver):
+ port = nameserver_ports.get(nameserver, default_port)
+ enriched_nameserver = dns.nameserver.Do53Nameserver(
+ nameserver, port
+ )
+ else:
+ try:
+ if urlparse(nameserver).scheme != "https":
+ raise NotImplementedError
+ except Exception:
+ raise ValueError(
+ f"nameserver {nameserver} is not a "
+ "dns.nameserver.Nameserver instance or text form, "
+ "IP address, nor a valid https URL"
+ )
+ enriched_nameserver = dns.nameserver.DoHNameserver(nameserver)
+ enriched_nameservers.append(enriched_nameserver)
+ else:
+ raise ValueError(
+ "nameservers must be a list or tuple (not a {})".format(
+ type(nameservers)
+ )
+ )
+ return enriched_nameservers
+
+ @property
+ def nameservers(
+ self,
+ ) -> Sequence[Union[str, dns.nameserver.Nameserver]]:
+ return self._nameservers
+
+ @nameservers.setter
+ def nameservers(
+ self, nameservers: Sequence[Union[str, dns.nameserver.Nameserver]]
+ ) -> None:
+ """
+ *nameservers*, a ``list`` of nameservers, where a nameserver is either
+ a string interpretable as a nameserver, or a ``dns.nameserver.Nameserver``
+ instance.
+
+ Raises ``ValueError`` if *nameservers* is not a list of nameservers.
+ """
+ # We just call _enrich_nameservers() for checking
+ self._enrich_nameservers(nameservers, self.nameserver_ports, self.port)
+ self._nameservers = nameservers
+
+
+class Resolver(BaseResolver):
+ """DNS stub resolver."""
+
+ def resolve(
+ self,
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+ search: Optional[bool] = None,
+ ) -> Answer: # pylint: disable=arguments-differ
+ """Query nameservers to find the answer to the question.
+
+ The *qname*, *rdtype*, and *rdclass* parameters may be objects
+ of the appropriate type, or strings that can be converted into objects
+ of the appropriate type.
+
+ *qname*, a ``dns.name.Name`` or ``str``, the query name.
+
+ *rdtype*, an ``int`` or ``str``, the query type.
+
+ *rdclass*, an ``int`` or ``str``, the query class.
+
+ *tcp*, a ``bool``. If ``True``, use TCP to make the query.
+
+ *source*, a ``str`` or ``None``. If not ``None``, bind to this IP
+ address when making queries.
+
+ *raise_on_no_answer*, a ``bool``. If ``True``, raise
+ ``dns.resolver.NoAnswer`` if there's no answer to the question.
+
+ *source_port*, an ``int``, the port from which to send the message.
+
+ *lifetime*, a ``float``, how many seconds a query should run
+ before timing out.
+
+ *search*, a ``bool`` or ``None``, determines whether the
+ search list configured in the system's resolver configuration
+ are used for relative names, and whether the resolver's domain
+ may be added to relative names. The default is ``None``,
+ which causes the value of the resolver's
+ ``use_search_by_default`` attribute to be used.
+
+ Raises ``dns.resolver.LifetimeTimeout`` if no answers could be found
+ in the specified lifetime.
+
+ Raises ``dns.resolver.NXDOMAIN`` if the query name does not exist.
+
+ Raises ``dns.resolver.YXDOMAIN`` if the query name is too long after
+ DNAME substitution.
+
+ Raises ``dns.resolver.NoAnswer`` if *raise_on_no_answer* is
+ ``True`` and the query name exists but has no RRset of the
+ desired type and class.
+
+ Raises ``dns.resolver.NoNameservers`` if no non-broken
+ nameservers are available to answer the question.
+
+ Returns a ``dns.resolver.Answer`` instance.
+
+ """
+
+ resolution = _Resolution(
+ self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search
+ )
+ start = time.time()
+ while True:
+ (request, answer) = resolution.next_request()
+ # Note we need to say "if answer is not None" and not just
+ # "if answer" because answer implements __len__, and python
+ # will call that. We want to return if we have an answer
+ # object, including in cases where its length is 0.
+ if answer is not None:
+ # cache hit!
+ return answer
+ assert request is not None # needed for type checking
+ done = False
+ while not done:
+ (nameserver, tcp, backoff) = resolution.next_nameserver()
+ if backoff:
+ time.sleep(backoff)
+ timeout = self._compute_timeout(start, lifetime, resolution.errors)
+ try:
+ response = nameserver.query(
+ request,
+ timeout=timeout,
+ source=source,
+ source_port=source_port,
+ max_size=tcp,
+ )
+ except Exception as ex:
+ (_, done) = resolution.query_result(None, ex)
+ continue
+ (answer, done) = resolution.query_result(response, None)
+ # Note we need to say "if answer is not None" and not just
+ # "if answer" because answer implements __len__, and python
+ # will call that. We want to return if we have an answer
+ # object, including in cases where its length is 0.
+ if answer is not None:
+ return answer
+
+ def query(
+ self,
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+ ) -> Answer: # pragma: no cover
+ """Query nameservers to find the answer to the question.
+
+ This method calls resolve() with ``search=True``, and is
+ provided for backwards compatibility with prior versions of
+ dnspython. See the documentation for the resolve() method for
+ further details.
+ """
+ warnings.warn(
+ "please use dns.resolver.Resolver.resolve() instead",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.resolve(
+ qname,
+ rdtype,
+ rdclass,
+ tcp,
+ source,
+ raise_on_no_answer,
+ source_port,
+ lifetime,
+ True,
+ )
+
+ def resolve_address(self, ipaddr: str, *args: Any, **kwargs: Any) -> Answer:
+ """Use a resolver to run a reverse query for PTR records.
+
+ This utilizes the resolve() method to perform a PTR lookup on the
+ specified IP address.
+
+ *ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get
+ the PTR record for.
+
+ All other arguments that can be passed to the resolve() function
+ except for rdtype and rdclass are also supported by this
+ function.
+ """
+ # We make a modified kwargs for type checking happiness, as otherwise
+ # we get a legit warning about possibly having rdtype and rdclass
+ # in the kwargs more than once.
+ modified_kwargs: Dict[str, Any] = {}
+ modified_kwargs.update(kwargs)
+ modified_kwargs["rdtype"] = dns.rdatatype.PTR
+ modified_kwargs["rdclass"] = dns.rdataclass.IN
+ return self.resolve(
+ dns.reversename.from_address(ipaddr), *args, **modified_kwargs
+ )
+
+ def resolve_name(
+ self,
+ name: Union[dns.name.Name, str],
+ family: int = socket.AF_UNSPEC,
+ **kwargs: Any,
+ ) -> HostAnswers:
+ """Use a resolver to query for address records.
+
+ This utilizes the resolve() method to perform A and/or AAAA lookups on
+ the specified name.
+
+ *qname*, a ``dns.name.Name`` or ``str``, the name to resolve.
+
+ *family*, an ``int``, the address family. If socket.AF_UNSPEC
+ (the default), both A and AAAA records will be retrieved.
+
+ All other arguments that can be passed to the resolve() function
+ except for rdtype and rdclass are also supported by this
+ function.
+ """
+ # We make a modified kwargs for type checking happiness, as otherwise
+ # we get a legit warning about possibly having rdtype and rdclass
+ # in the kwargs more than once.
+ modified_kwargs: Dict[str, Any] = {}
+ modified_kwargs.update(kwargs)
+ modified_kwargs.pop("rdtype", None)
+ modified_kwargs["rdclass"] = dns.rdataclass.IN
+
+ if family == socket.AF_INET:
+ v4 = self.resolve(name, dns.rdatatype.A, **modified_kwargs)
+ return HostAnswers.make(v4=v4)
+ elif family == socket.AF_INET6:
+ v6 = self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs)
+ return HostAnswers.make(v6=v6)
+ elif family != socket.AF_UNSPEC:
+ raise NotImplementedError(f"unknown address family {family}")
+
+ raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True)
+ lifetime = modified_kwargs.pop("lifetime", None)
+ start = time.time()
+ v6 = self.resolve(
+ name,
+ dns.rdatatype.AAAA,
+ raise_on_no_answer=False,
+ lifetime=self._compute_timeout(start, lifetime),
+ **modified_kwargs,
+ )
+ # Note that setting name ensures we query the same name
+ # for A as we did for AAAA. (This is just in case search lists
+ # are active by default in the resolver configuration and
+ # we might be talking to a server that says NXDOMAIN when it
+ # wants to say NOERROR no data.
+ name = v6.qname
+ v4 = self.resolve(
+ name,
+ dns.rdatatype.A,
+ raise_on_no_answer=False,
+ lifetime=self._compute_timeout(start, lifetime),
+ **modified_kwargs,
+ )
+ answers = HostAnswers.make(v6=v6, v4=v4, add_empty=not raise_on_no_answer)
+ if not answers:
+ raise NoAnswer(response=v6.response)
+ return answers
+
+ # pylint: disable=redefined-outer-name
+
+ def canonical_name(self, name: Union[dns.name.Name, str]) -> dns.name.Name:
+ """Determine the canonical name of *name*.
+
+ The canonical name is the name the resolver uses for queries
+ after all CNAME and DNAME renamings have been applied.
+
+ *name*, a ``dns.name.Name`` or ``str``, the query name.
+
+ This method can raise any exception that ``resolve()`` can
+ raise, other than ``dns.resolver.NoAnswer`` and
+ ``dns.resolver.NXDOMAIN``.
+
+ Returns a ``dns.name.Name``.
+ """
+ try:
+ answer = self.resolve(name, raise_on_no_answer=False)
+ canonical_name = answer.canonical_name
+ except dns.resolver.NXDOMAIN as e:
+ canonical_name = e.canonical_name
+ return canonical_name
+
+ # pylint: enable=redefined-outer-name
+
+ def try_ddr(self, lifetime: float = 5.0) -> None:
+ """Try to update the resolver's nameservers using Discovery of Designated
+ Resolvers (DDR). If successful, the resolver will subsequently use
+ DNS-over-HTTPS or DNS-over-TLS for future queries.
+
+ *lifetime*, a float, is the maximum time to spend attempting DDR. The default
+ is 5 seconds.
+
+ If the SVCB query is successful and results in a non-empty list of nameservers,
+ then the resolver's nameservers are set to the returned servers in priority
+ order.
+
+ The current implementation does not use any address hints from the SVCB record,
+ nor does it resolve addresses for the SCVB target name, rather it assumes that
+ the bootstrap nameserver will always be one of the addresses and uses it.
+ A future revision to the code may offer fuller support. The code verifies that
+ the bootstrap nameserver is in the Subject Alternative Name field of the
+ TLS certficate.
+ """
+ try:
+ expiration = time.time() + lifetime
+ answer = self.resolve(
+ dns._ddr._local_resolver_name, "SVCB", lifetime=lifetime
+ )
+ timeout = dns.query._remaining(expiration)
+ nameservers = dns._ddr._get_nameservers_sync(answer, timeout)
+ if len(nameservers) > 0:
+ self.nameservers = nameservers
+ except Exception:
+ pass
+
+
+#: The default resolver.
+default_resolver: Optional[Resolver] = None
+
+
+def get_default_resolver() -> Resolver:
+ """Get the default resolver, initializing it if necessary."""
+ if default_resolver is None:
+ reset_default_resolver()
+ assert default_resolver is not None
+ return default_resolver
+
+
+def reset_default_resolver() -> None:
+ """Re-initialize default resolver.
+
+ Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX
+ systems) will be re-read immediately.
+ """
+
+ global default_resolver
+ default_resolver = Resolver()
+
+
+def resolve(
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+ search: Optional[bool] = None,
+) -> Answer: # pragma: no cover
+ """Query nameservers to find the answer to the question.
+
+ This is a convenience function that uses the default resolver
+ object to make the query.
+
+ See ``dns.resolver.Resolver.resolve`` for more information on the
+ parameters.
+ """
+
+ return get_default_resolver().resolve(
+ qname,
+ rdtype,
+ rdclass,
+ tcp,
+ source,
+ raise_on_no_answer,
+ source_port,
+ lifetime,
+ search,
+ )
+
+
+def query(
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+) -> Answer: # pragma: no cover
+ """Query nameservers to find the answer to the question.
+
+ This method calls resolve() with ``search=True``, and is
+ provided for backwards compatibility with prior versions of
+ dnspython. See the documentation for the resolve() method for
+ further details.
+ """
+ warnings.warn(
+ "please use dns.resolver.resolve() instead", DeprecationWarning, stacklevel=2
+ )
+ return resolve(
+ qname,
+ rdtype,
+ rdclass,
+ tcp,
+ source,
+ raise_on_no_answer,
+ source_port,
+ lifetime,
+ True,
+ )
+
+
+def resolve_address(ipaddr: str, *args: Any, **kwargs: Any) -> Answer:
+ """Use a resolver to run a reverse query for PTR records.
+
+ See ``dns.resolver.Resolver.resolve_address`` for more information on the
+ parameters.
+ """
+
+ return get_default_resolver().resolve_address(ipaddr, *args, **kwargs)
+
+
+def resolve_name(
+ name: Union[dns.name.Name, str], family: int = socket.AF_UNSPEC, **kwargs: Any
+) -> HostAnswers:
+ """Use a resolver to query for address records.
+
+ See ``dns.resolver.Resolver.resolve_name`` for more information on the
+ parameters.
+ """
+
+ return get_default_resolver().resolve_name(name, family, **kwargs)
+
+
+def canonical_name(name: Union[dns.name.Name, str]) -> dns.name.Name:
+ """Determine the canonical name of *name*.
+
+ See ``dns.resolver.Resolver.canonical_name`` for more information on the
+ parameters and possible exceptions.
+ """
+
+ return get_default_resolver().canonical_name(name)
+
+
+def try_ddr(lifetime: float = 5.0) -> None:
+ """Try to update the default resolver's nameservers using Discovery of Designated
+ Resolvers (DDR). If successful, the resolver will subsequently use
+ DNS-over-HTTPS or DNS-over-TLS for future queries.
+
+ See :py:func:`dns.resolver.Resolver.try_ddr` for more information.
+ """
+ return get_default_resolver().try_ddr(lifetime)
+
+
+def zone_for_name(
+ name: Union[dns.name.Name, str],
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ tcp: bool = False,
+ resolver: Optional[Resolver] = None,
+ lifetime: Optional[float] = None,
+) -> dns.name.Name:
+ """Find the name of the zone which contains the specified name.
+
+ *name*, an absolute ``dns.name.Name`` or ``str``, the query name.
+
+ *rdclass*, an ``int``, the query class.
+
+ *tcp*, a ``bool``. If ``True``, use TCP to make the query.
+
+ *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use.
+ If ``None``, the default, then the default resolver is used.
+
+ *lifetime*, a ``float``, the total time to allow for the queries needed
+ to determine the zone. If ``None``, the default, then only the individual
+ query limits of the resolver apply.
+
+ Raises ``dns.resolver.NoRootSOA`` if there is no SOA RR at the DNS
+ root. (This is only likely to happen if you're using non-default
+ root servers in your network and they are misconfigured.)
+
+ Raises ``dns.resolver.LifetimeTimeout`` if the answer could not be
+ found in the allotted lifetime.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, dns.name.root)
+ if resolver is None:
+ resolver = get_default_resolver()
+ if not name.is_absolute():
+ raise NotAbsolute(name)
+ start = time.time()
+ expiration: Optional[float]
+ if lifetime is not None:
+ expiration = start + lifetime
+ else:
+ expiration = None
+ while 1:
+ try:
+ rlifetime: Optional[float]
+ if expiration is not None:
+ rlifetime = expiration - time.time()
+ if rlifetime <= 0:
+ rlifetime = 0
+ else:
+ rlifetime = None
+ answer = resolver.resolve(
+ name, dns.rdatatype.SOA, rdclass, tcp, lifetime=rlifetime
+ )
+ assert answer.rrset is not None
+ if answer.rrset.name == name:
+ return name
+ # otherwise we were CNAMEd or DNAMEd and need to look higher
+ except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer) as e:
+ if isinstance(e, dns.resolver.NXDOMAIN):
+ response = e.responses().get(name)
+ else:
+ response = e.response() # pylint: disable=no-value-for-parameter
+ if response:
+ for rrs in response.authority:
+ if rrs.rdtype == dns.rdatatype.SOA and rrs.rdclass == rdclass:
+ (nr, _, _) = rrs.name.fullcompare(name)
+ if nr == dns.name.NAMERELN_SUPERDOMAIN:
+ # We're doing a proper superdomain check as
+ # if the name were equal we ought to have gotten
+ # it in the answer section! We are ignoring the
+ # possibility that the authority is insane and
+ # is including multiple SOA RRs for different
+ # authorities.
+ return rrs.name
+ # we couldn't extract anything useful from the response (e.g. it's
+ # a type 3 NXDOMAIN)
+ try:
+ name = name.parent()
+ except dns.name.NoParent:
+ raise NoRootSOA
+
+
+def make_resolver_at(
+ where: Union[dns.name.Name, str],
+ port: int = 53,
+ family: int = socket.AF_UNSPEC,
+ resolver: Optional[Resolver] = None,
+) -> Resolver:
+ """Make a stub resolver using the specified destination as the full resolver.
+
+ *where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the
+ full resolver.
+
+ *port*, an ``int``, the port to use. If not specified, the default is 53.
+
+ *family*, an ``int``, the address family to use. This parameter is used if
+ *where* is not an address. The default is ``socket.AF_UNSPEC`` in which case
+ the first address returned by ``resolve_name()`` will be used, otherwise the
+ first address of the specified family will be used.
+
+ *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for
+ resolution of hostnames. If not specified, the default resolver will be used.
+
+ Returns a ``dns.resolver.Resolver`` or raises an exception.
+ """
+ if resolver is None:
+ resolver = get_default_resolver()
+ nameservers: List[Union[str, dns.nameserver.Nameserver]] = []
+ if isinstance(where, str) and dns.inet.is_address(where):
+ nameservers.append(dns.nameserver.Do53Nameserver(where, port))
+ else:
+ for address in resolver.resolve_name(where, family).addresses():
+ nameservers.append(dns.nameserver.Do53Nameserver(address, port))
+ res = dns.resolver.Resolver(configure=False)
+ res.nameservers = nameservers
+ return res
+
+
+def resolve_at(
+ where: Union[dns.name.Name, str],
+ qname: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
+ rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ tcp: bool = False,
+ source: Optional[str] = None,
+ raise_on_no_answer: bool = True,
+ source_port: int = 0,
+ lifetime: Optional[float] = None,
+ search: Optional[bool] = None,
+ port: int = 53,
+ family: int = socket.AF_UNSPEC,
+ resolver: Optional[Resolver] = None,
+) -> Answer:
+ """Query nameservers to find the answer to the question.
+
+ This is a convenience function that calls ``dns.resolver.make_resolver_at()`` to
+ make a resolver, and then uses it to resolve the query.
+
+ See ``dns.resolver.Resolver.resolve`` for more information on the resolution
+ parameters, and ``dns.resolver.make_resolver_at`` for information about the resolver
+ parameters *where*, *port*, *family*, and *resolver*.
+
+ If making more than one query, it is more efficient to call
+ ``dns.resolver.make_resolver_at()`` and then use that resolver for the queries
+ instead of calling ``resolve_at()`` multiple times.
+ """
+ return make_resolver_at(where, port, family, resolver).resolve(
+ qname,
+ rdtype,
+ rdclass,
+ tcp,
+ source,
+ raise_on_no_answer,
+ source_port,
+ lifetime,
+ search,
+ )
+
+
+#
+# Support for overriding the system resolver for all python code in the
+# running process.
+#
+
+_protocols_for_socktype = {
+ socket.SOCK_DGRAM: [socket.SOL_UDP],
+ socket.SOCK_STREAM: [socket.SOL_TCP],
+}
+
+_resolver = None
+_original_getaddrinfo = socket.getaddrinfo
+_original_getnameinfo = socket.getnameinfo
+_original_getfqdn = socket.getfqdn
+_original_gethostbyname = socket.gethostbyname
+_original_gethostbyname_ex = socket.gethostbyname_ex
+_original_gethostbyaddr = socket.gethostbyaddr
+
+
+def _getaddrinfo(
+ host=None, service=None, family=socket.AF_UNSPEC, socktype=0, proto=0, flags=0
+):
+ if flags & socket.AI_NUMERICHOST != 0:
+ # Short circuit directly into the system's getaddrinfo(). We're
+ # not adding any value in this case, and this avoids infinite loops
+ # because dns.query.* needs to call getaddrinfo() for IPv6 scoping
+ # reasons. We will also do this short circuit below if we
+ # discover that the host is an address literal.
+ return _original_getaddrinfo(host, service, family, socktype, proto, flags)
+ if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0:
+ # Not implemented. We raise a gaierror as opposed to a
+ # NotImplementedError as it helps callers handle errors more
+ # appropriately. [Issue #316]
+ #
+ # We raise EAI_FAIL as opposed to EAI_SYSTEM because there is
+ # no EAI_SYSTEM on Windows [Issue #416]. We didn't go for
+ # EAI_BADFLAGS as the flags aren't bad, we just don't
+ # implement them.
+ raise socket.gaierror(
+ socket.EAI_FAIL, "Non-recoverable failure in name resolution"
+ )
+ if host is None and service is None:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")
+ addrs = []
+ canonical_name = None # pylint: disable=redefined-outer-name
+ # Is host None or an address literal? If so, use the system's
+ # getaddrinfo().
+ if host is None:
+ return _original_getaddrinfo(host, service, family, socktype, proto, flags)
+ try:
+ # We don't care about the result of af_for_address(), we're just
+ # calling it so it raises an exception if host is not an IPv4 or
+ # IPv6 address.
+ dns.inet.af_for_address(host)
+ return _original_getaddrinfo(host, service, family, socktype, proto, flags)
+ except Exception:
+ pass
+ # Something needs resolution!
+ try:
+ answers = _resolver.resolve_name(host, family)
+ addrs = answers.addresses_and_families()
+ canonical_name = answers.canonical_name().to_text(True)
+ except dns.resolver.NXDOMAIN:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")
+ except Exception:
+ # We raise EAI_AGAIN here as the failure may be temporary
+ # (e.g. a timeout) and EAI_SYSTEM isn't defined on Windows.
+ # [Issue #416]
+ raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")
+ port = None
+ try:
+ # Is it a port literal?
+ if service is None:
+ port = 0
+ else:
+ port = int(service)
+ except Exception:
+ if flags & socket.AI_NUMERICSERV == 0:
+ try:
+ port = socket.getservbyname(service)
+ except Exception:
+ pass
+ if port is None:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")
+ tuples = []
+ if socktype == 0:
+ socktypes = [socket.SOCK_DGRAM, socket.SOCK_STREAM]
+ else:
+ socktypes = [socktype]
+ if flags & socket.AI_CANONNAME != 0:
+ cname = canonical_name
+ else:
+ cname = ""
+ for addr, af in addrs:
+ for socktype in socktypes:
+ for proto in _protocols_for_socktype[socktype]:
+ addr_tuple = dns.inet.low_level_address_tuple((addr, port), af)
+ tuples.append((af, socktype, proto, cname, addr_tuple))
+ if len(tuples) == 0:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")
+ return tuples
+
+
+def _getnameinfo(sockaddr, flags=0):
+ host = sockaddr[0]
+ port = sockaddr[1]
+ if len(sockaddr) == 4:
+ scope = sockaddr[3]
+ family = socket.AF_INET6
+ else:
+ scope = None
+ family = socket.AF_INET
+ tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0)
+ if len(tuples) > 1:
+ raise socket.error("sockaddr resolved to multiple addresses")
+ addr = tuples[0][4][0]
+ if flags & socket.NI_DGRAM:
+ pname = "udp"
+ else:
+ pname = "tcp"
+ qname = dns.reversename.from_address(addr)
+ if flags & socket.NI_NUMERICHOST == 0:
+ try:
+ answer = _resolver.resolve(qname, "PTR")
+ hostname = answer.rrset[0].target.to_text(True)
+ except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
+ if flags & socket.NI_NAMEREQD:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")
+ hostname = addr
+ if scope is not None:
+ hostname += "%" + str(scope)
+ else:
+ hostname = addr
+ if scope is not None:
+ hostname += "%" + str(scope)
+ if flags & socket.NI_NUMERICSERV:
+ service = str(port)
+ else:
+ service = socket.getservbyport(port, pname)
+ return (hostname, service)
+
+
+def _getfqdn(name=None):
+ if name is None:
+ name = socket.gethostname()
+ try:
+ (name, _, _) = _gethostbyaddr(name)
+ # Python's version checks aliases too, but our gethostbyname
+ # ignores them, so we do so here as well.
+ except Exception:
+ pass
+ return name
+
+
+def _gethostbyname(name):
+ return _gethostbyname_ex(name)[2][0]
+
+
+def _gethostbyname_ex(name):
+ aliases = []
+ addresses = []
+ tuples = _getaddrinfo(
+ name, 0, socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME
+ )
+ canonical = tuples[0][3]
+ for item in tuples:
+ addresses.append(item[4][0])
+ # XXX we just ignore aliases
+ return (canonical, aliases, addresses)
+
+
+def _gethostbyaddr(ip):
+ try:
+ dns.ipv6.inet_aton(ip)
+ sockaddr = (ip, 80, 0, 0)
+ family = socket.AF_INET6
+ except Exception:
+ try:
+ dns.ipv4.inet_aton(ip)
+ except Exception:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")
+ sockaddr = (ip, 80)
+ family = socket.AF_INET
+ (name, _) = _getnameinfo(sockaddr, socket.NI_NAMEREQD)
+ aliases = []
+ addresses = []
+ tuples = _getaddrinfo(
+ name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME
+ )
+ canonical = tuples[0][3]
+ # We only want to include an address from the tuples if it's the
+ # same as the one we asked about. We do this comparison in binary
+ # to avoid any differences in text representations.
+ bin_ip = dns.inet.inet_pton(family, ip)
+ for item in tuples:
+ addr = item[4][0]
+ bin_addr = dns.inet.inet_pton(family, addr)
+ if bin_ip == bin_addr:
+ addresses.append(addr)
+ # XXX we just ignore aliases
+ return (canonical, aliases, addresses)
+
+
+def override_system_resolver(resolver: Optional[Resolver] = None) -> None:
+ """Override the system resolver routines in the socket module with
+ versions which use dnspython's resolver.
+
+ This can be useful in testing situations where you want to control
+ the resolution behavior of python code without having to change
+ the system's resolver settings (e.g. /etc/resolv.conf).
+
+ The resolver to use may be specified; if it's not, the default
+ resolver will be used.
+
+ resolver, a ``dns.resolver.Resolver`` or ``None``, the resolver to use.
+ """
+
+ if resolver is None:
+ resolver = get_default_resolver()
+ global _resolver
+ _resolver = resolver
+ socket.getaddrinfo = _getaddrinfo
+ socket.getnameinfo = _getnameinfo
+ socket.getfqdn = _getfqdn
+ socket.gethostbyname = _gethostbyname
+ socket.gethostbyname_ex = _gethostbyname_ex
+ socket.gethostbyaddr = _gethostbyaddr
+
+
+def restore_system_resolver() -> None:
+ """Undo the effects of prior override_system_resolver()."""
+
+ global _resolver
+ _resolver = None
+ socket.getaddrinfo = _original_getaddrinfo
+ socket.getnameinfo = _original_getnameinfo
+ socket.getfqdn = _original_getfqdn
+ socket.gethostbyname = _original_gethostbyname
+ socket.gethostbyname_ex = _original_gethostbyname_ex
+ socket.gethostbyaddr = _original_gethostbyaddr
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/reversename.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/reversename.py
new file mode 100644
index 0000000000000000000000000000000000000000..8236c711f16f1e3b514f182a8254cb0e0ce45a68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/reversename.py
@@ -0,0 +1,105 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2006-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Reverse Map Names."""
+
+import binascii
+
+import dns.ipv4
+import dns.ipv6
+import dns.name
+
+ipv4_reverse_domain = dns.name.from_text("in-addr.arpa.")
+ipv6_reverse_domain = dns.name.from_text("ip6.arpa.")
+
+
+def from_address(
+ text: str,
+ v4_origin: dns.name.Name = ipv4_reverse_domain,
+ v6_origin: dns.name.Name = ipv6_reverse_domain,
+) -> dns.name.Name:
+ """Convert an IPv4 or IPv6 address in textual form into a Name object whose
+ value is the reverse-map domain name of the address.
+
+ *text*, a ``str``, is an IPv4 or IPv6 address in textual form
+ (e.g. '127.0.0.1', '::1')
+
+ *v4_origin*, a ``dns.name.Name`` to append to the labels corresponding to
+ the address if the address is an IPv4 address, instead of the default
+ (in-addr.arpa.)
+
+ *v6_origin*, a ``dns.name.Name`` to append to the labels corresponding to
+ the address if the address is an IPv6 address, instead of the default
+ (ip6.arpa.)
+
+ Raises ``dns.exception.SyntaxError`` if the address is badly formed.
+
+ Returns a ``dns.name.Name``.
+ """
+
+ try:
+ v6 = dns.ipv6.inet_aton(text)
+ if dns.ipv6.is_mapped(v6):
+ parts = ["%d" % byte for byte in v6[12:]]
+ origin = v4_origin
+ else:
+ parts = [x for x in str(binascii.hexlify(v6).decode())]
+ origin = v6_origin
+ except Exception:
+ parts = ["%d" % byte for byte in dns.ipv4.inet_aton(text)]
+ origin = v4_origin
+ return dns.name.from_text(".".join(reversed(parts)), origin=origin)
+
+
+def to_address(
+ name: dns.name.Name,
+ v4_origin: dns.name.Name = ipv4_reverse_domain,
+ v6_origin: dns.name.Name = ipv6_reverse_domain,
+) -> str:
+ """Convert a reverse map domain name into textual address form.
+
+ *name*, a ``dns.name.Name``, an IPv4 or IPv6 address in reverse-map name
+ form.
+
+ *v4_origin*, a ``dns.name.Name`` representing the top-level domain for
+ IPv4 addresses, instead of the default (in-addr.arpa.)
+
+ *v6_origin*, a ``dns.name.Name`` representing the top-level domain for
+ IPv4 addresses, instead of the default (ip6.arpa.)
+
+ Raises ``dns.exception.SyntaxError`` if the name does not have a
+ reverse-map form.
+
+ Returns a ``str``.
+ """
+
+ if name.is_subdomain(v4_origin):
+ name = name.relativize(v4_origin)
+ text = b".".join(reversed(name.labels))
+ # run through inet_ntoa() to check syntax and make pretty.
+ return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text))
+ elif name.is_subdomain(v6_origin):
+ name = name.relativize(v6_origin)
+ labels = list(reversed(name.labels))
+ parts = []
+ for i in range(0, len(labels), 4):
+ parts.append(b"".join(labels[i : i + 4]))
+ text = b":".join(parts)
+ # run through inet_ntoa() to check syntax and make pretty.
+ return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text))
+ else:
+ raise dns.exception.SyntaxError("unknown reverse-map address family")
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rrset.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rrset.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f39b108db9f3ea4a8955a38e326511394092363
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/rrset.py
@@ -0,0 +1,285 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS RRsets (an RRset is a named rdataset)"""
+
+from typing import Any, Collection, Dict, Optional, Union, cast
+
+import dns.name
+import dns.rdataclass
+import dns.rdataset
+import dns.renderer
+
+
+class RRset(dns.rdataset.Rdataset):
+ """A DNS RRset (named rdataset).
+
+ RRset inherits from Rdataset, and RRsets can be treated as
+ Rdatasets in most cases. There are, however, a few notable
+ exceptions. RRsets have different to_wire() and to_text() method
+ arguments, reflecting the fact that RRsets always have an owner
+ name.
+ """
+
+ __slots__ = ["name", "deleting"]
+
+ def __init__(
+ self,
+ name: dns.name.Name,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ deleting: Optional[dns.rdataclass.RdataClass] = None,
+ ):
+ """Create a new RRset."""
+
+ super().__init__(rdclass, rdtype, covers)
+ self.name = name
+ self.deleting = deleting
+
+ def _clone(self):
+ obj = super()._clone()
+ obj.name = self.name
+ obj.deleting = self.deleting
+ return obj
+
+ def __repr__(self):
+ if self.covers == 0:
+ ctext = ""
+ else:
+ ctext = "(" + dns.rdatatype.to_text(self.covers) + ")"
+ if self.deleting is not None:
+ dtext = " delete=" + dns.rdataclass.to_text(self.deleting)
+ else:
+ dtext = ""
+ return (
+ ""
+ )
+
+ def __str__(self):
+ return self.to_text()
+
+ def __eq__(self, other):
+ if isinstance(other, RRset):
+ if self.name != other.name:
+ return False
+ elif not isinstance(other, dns.rdataset.Rdataset):
+ return False
+ return super().__eq__(other)
+
+ def match(self, *args: Any, **kwargs: Any) -> bool: # type: ignore[override]
+ """Does this rrset match the specified attributes?
+
+ Behaves as :py:func:`full_match()` if the first argument is a
+ ``dns.name.Name``, and as :py:func:`dns.rdataset.Rdataset.match()`
+ otherwise.
+
+ (This behavior fixes a design mistake where the signature of this
+ method became incompatible with that of its superclass. The fix
+ makes RRsets matchable as Rdatasets while preserving backwards
+ compatibility.)
+ """
+ if isinstance(args[0], dns.name.Name):
+ return self.full_match(*args, **kwargs) # type: ignore[arg-type]
+ else:
+ return super().match(*args, **kwargs) # type: ignore[arg-type]
+
+ def full_match(
+ self,
+ name: dns.name.Name,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType,
+ deleting: Optional[dns.rdataclass.RdataClass] = None,
+ ) -> bool:
+ """Returns ``True`` if this rrset matches the specified name, class,
+ type, covers, and deletion state.
+ """
+ if not super().match(rdclass, rdtype, covers):
+ return False
+ if self.name != name or self.deleting != deleting:
+ return False
+ return True
+
+ # pylint: disable=arguments-differ
+
+ def to_text( # type: ignore[override]
+ self,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ **kw: Dict[str, Any],
+ ) -> str:
+ """Convert the RRset into DNS zone file format.
+
+ See ``dns.name.Name.choose_relativity`` for more information
+ on how *origin* and *relativize* determine the way names
+ are emitted.
+
+ Any additional keyword arguments are passed on to the rdata
+ ``to_text()`` method.
+
+ *origin*, a ``dns.name.Name`` or ``None``, the origin for relative
+ names.
+
+ *relativize*, a ``bool``. If ``True``, names will be relativized
+ to *origin*.
+ """
+
+ return super().to_text(
+ self.name, origin, relativize, self.deleting, **kw # type: ignore
+ )
+
+ def to_wire( # type: ignore[override]
+ self,
+ file: Any,
+ compress: Optional[dns.name.CompressType] = None, # type: ignore
+ origin: Optional[dns.name.Name] = None,
+ **kw: Dict[str, Any],
+ ) -> int:
+ """Convert the RRset to wire format.
+
+ All keyword arguments are passed to ``dns.rdataset.to_wire()``; see
+ that function for details.
+
+ Returns an ``int``, the number of records emitted.
+ """
+
+ return super().to_wire(
+ self.name, file, compress, origin, self.deleting, **kw # type:ignore
+ )
+
+ # pylint: enable=arguments-differ
+
+ def to_rdataset(self) -> dns.rdataset.Rdataset:
+ """Convert an RRset into an Rdataset.
+
+ Returns a ``dns.rdataset.Rdataset``.
+ """
+ return dns.rdataset.from_rdata_list(self.ttl, list(self))
+
+
+def from_text_list(
+ name: Union[dns.name.Name, str],
+ ttl: int,
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ text_rdatas: Collection[str],
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = True,
+ relativize_to: Optional[dns.name.Name] = None,
+) -> RRset:
+ """Create an RRset with the specified name, TTL, class, and type, and with
+ the specified list of rdatas in text format.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder to use; if ``None``, the default IDNA 2003
+ encoder/decoder is used.
+
+ *origin*, a ``dns.name.Name`` (or ``None``), the
+ origin to use for relative names.
+
+ *relativize*, a ``bool``. If true, name will be relativized.
+
+ *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
+ when relativizing names. If not set, the *origin* value will be used.
+
+ Returns a ``dns.rrset.RRset`` object.
+ """
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None, idna_codec=idna_codec)
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ r = RRset(name, rdclass, rdtype)
+ r.update_ttl(ttl)
+ for t in text_rdatas:
+ rd = dns.rdata.from_text(
+ r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec
+ )
+ r.add(rd)
+ return r
+
+
+def from_text(
+ name: Union[dns.name.Name, str],
+ ttl: int,
+ rdclass: Union[dns.rdataclass.RdataClass, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ *text_rdatas: Any,
+) -> RRset:
+ """Create an RRset with the specified name, TTL, class, and type and with
+ the specified rdatas in text format.
+
+ Returns a ``dns.rrset.RRset`` object.
+ """
+
+ return from_text_list(
+ name, ttl, rdclass, rdtype, cast(Collection[str], text_rdatas)
+ )
+
+
+def from_rdata_list(
+ name: Union[dns.name.Name, str],
+ ttl: int,
+ rdatas: Collection[dns.rdata.Rdata],
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+) -> RRset:
+ """Create an RRset with the specified name and TTL, and with
+ the specified list of rdata objects.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder to use; if ``None``, the default IDNA 2003
+ encoder/decoder is used.
+
+ Returns a ``dns.rrset.RRset`` object.
+
+ """
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None, idna_codec=idna_codec)
+
+ if len(rdatas) == 0:
+ raise ValueError("rdata list must not be empty")
+ r = None
+ for rd in rdatas:
+ if r is None:
+ r = RRset(name, rd.rdclass, rd.rdtype)
+ r.update_ttl(ttl)
+ r.add(rd)
+ assert r is not None
+ return r
+
+
+def from_rdata(name: Union[dns.name.Name, str], ttl: int, *rdatas: Any) -> RRset:
+ """Create an RRset with the specified name and TTL, and with
+ the specified rdata objects.
+
+ Returns a ``dns.rrset.RRset`` object.
+ """
+
+ return from_rdata_list(name, ttl, cast(Collection[dns.rdata.Rdata], rdatas))
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/serial.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/serial.py
new file mode 100644
index 0000000000000000000000000000000000000000..3417299be2bbb3726780f1ebf74bb16974cae308
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/serial.py
@@ -0,0 +1,118 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+"""Serial Number Arthimetic from RFC 1982"""
+
+
+class Serial:
+ def __init__(self, value: int, bits: int = 32):
+ self.value = value % 2**bits
+ self.bits = bits
+
+ def __repr__(self):
+ return f"dns.serial.Serial({self.value}, {self.bits})"
+
+ def __eq__(self, other):
+ if isinstance(other, int):
+ other = Serial(other, self.bits)
+ elif not isinstance(other, Serial) or other.bits != self.bits:
+ return NotImplemented
+ return self.value == other.value
+
+ def __ne__(self, other):
+ if isinstance(other, int):
+ other = Serial(other, self.bits)
+ elif not isinstance(other, Serial) or other.bits != self.bits:
+ return NotImplemented
+ return self.value != other.value
+
+ def __lt__(self, other):
+ if isinstance(other, int):
+ other = Serial(other, self.bits)
+ elif not isinstance(other, Serial) or other.bits != self.bits:
+ return NotImplemented
+ if self.value < other.value and other.value - self.value < 2 ** (self.bits - 1):
+ return True
+ elif self.value > other.value and self.value - other.value > 2 ** (
+ self.bits - 1
+ ):
+ return True
+ else:
+ return False
+
+ def __le__(self, other):
+ return self == other or self < other
+
+ def __gt__(self, other):
+ if isinstance(other, int):
+ other = Serial(other, self.bits)
+ elif not isinstance(other, Serial) or other.bits != self.bits:
+ return NotImplemented
+ if self.value < other.value and other.value - self.value > 2 ** (self.bits - 1):
+ return True
+ elif self.value > other.value and self.value - other.value < 2 ** (
+ self.bits - 1
+ ):
+ return True
+ else:
+ return False
+
+ def __ge__(self, other):
+ return self == other or self > other
+
+ def __add__(self, other):
+ v = self.value
+ if isinstance(other, Serial):
+ delta = other.value
+ elif isinstance(other, int):
+ delta = other
+ else:
+ raise ValueError
+ if abs(delta) > (2 ** (self.bits - 1) - 1):
+ raise ValueError
+ v += delta
+ v = v % 2**self.bits
+ return Serial(v, self.bits)
+
+ def __iadd__(self, other):
+ v = self.value
+ if isinstance(other, Serial):
+ delta = other.value
+ elif isinstance(other, int):
+ delta = other
+ else:
+ raise ValueError
+ if abs(delta) > (2 ** (self.bits - 1) - 1):
+ raise ValueError
+ v += delta
+ v = v % 2**self.bits
+ self.value = v
+ return self
+
+ def __sub__(self, other):
+ v = self.value
+ if isinstance(other, Serial):
+ delta = other.value
+ elif isinstance(other, int):
+ delta = other
+ else:
+ raise ValueError
+ if abs(delta) > (2 ** (self.bits - 1) - 1):
+ raise ValueError
+ v -= delta
+ v = v % 2**self.bits
+ return Serial(v, self.bits)
+
+ def __isub__(self, other):
+ v = self.value
+ if isinstance(other, Serial):
+ delta = other.value
+ elif isinstance(other, int):
+ delta = other
+ else:
+ raise ValueError
+ if abs(delta) > (2 ** (self.bits - 1) - 1):
+ raise ValueError
+ v -= delta
+ v = v % 2**self.bits
+ self.value = v
+ return self
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/set.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/set.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0fb0d50d33b872bb1ca9a113905135fe9941e08
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/set.py
@@ -0,0 +1,307 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+import itertools
+
+
+class Set:
+ """A simple set class.
+
+ This class was originally used to deal with sets being missing in
+ ancient versions of python, but dnspython will continue to use it
+ as these sets are based on lists and are thus indexable, and this
+ ability is widely used in dnspython applications.
+ """
+
+ __slots__ = ["items"]
+
+ def __init__(self, items=None):
+ """Initialize the set.
+
+ *items*, an iterable or ``None``, the initial set of items.
+ """
+
+ self.items = dict()
+ if items is not None:
+ for item in items:
+ # This is safe for how we use set, but if other code
+ # subclasses it could be a legitimate issue.
+ self.add(item) # lgtm[py/init-calls-subclass]
+
+ def __repr__(self):
+ return "dns.set.Set(%s)" % repr(list(self.items.keys()))
+
+ def add(self, item):
+ """Add an item to the set."""
+
+ if item not in self.items:
+ self.items[item] = None
+
+ def remove(self, item):
+ """Remove an item from the set."""
+
+ try:
+ del self.items[item]
+ except KeyError:
+ raise ValueError
+
+ def discard(self, item):
+ """Remove an item from the set if present."""
+
+ self.items.pop(item, None)
+
+ def pop(self):
+ """Remove an arbitrary item from the set."""
+ (k, _) = self.items.popitem()
+ return k
+
+ def _clone(self) -> "Set":
+ """Make a (shallow) copy of the set.
+
+ There is a 'clone protocol' that subclasses of this class
+ should use. To make a copy, first call your super's _clone()
+ method, and use the object returned as the new instance. Then
+ make shallow copies of the attributes defined in the subclass.
+
+ This protocol allows us to write the set algorithms that
+ return new instances (e.g. union) once, and keep using them in
+ subclasses.
+ """
+
+ if hasattr(self, "_clone_class"):
+ cls = self._clone_class # type: ignore
+ else:
+ cls = self.__class__
+ obj = cls.__new__(cls)
+ obj.items = dict()
+ obj.items.update(self.items)
+ return obj
+
+ def __copy__(self):
+ """Make a (shallow) copy of the set."""
+
+ return self._clone()
+
+ def copy(self):
+ """Make a (shallow) copy of the set."""
+
+ return self._clone()
+
+ def union_update(self, other):
+ """Update the set, adding any elements from other which are not
+ already in the set.
+ """
+
+ if not isinstance(other, Set):
+ raise ValueError("other must be a Set instance")
+ if self is other: # lgtm[py/comparison-using-is]
+ return
+ for item in other.items:
+ self.add(item)
+
+ def intersection_update(self, other):
+ """Update the set, removing any elements from other which are not
+ in both sets.
+ """
+
+ if not isinstance(other, Set):
+ raise ValueError("other must be a Set instance")
+ if self is other: # lgtm[py/comparison-using-is]
+ return
+ # we make a copy of the list so that we can remove items from
+ # the list without breaking the iterator.
+ for item in list(self.items):
+ if item not in other.items:
+ del self.items[item]
+
+ def difference_update(self, other):
+ """Update the set, removing any elements from other which are in
+ the set.
+ """
+
+ if not isinstance(other, Set):
+ raise ValueError("other must be a Set instance")
+ if self is other: # lgtm[py/comparison-using-is]
+ self.items.clear()
+ else:
+ for item in other.items:
+ self.discard(item)
+
+ def symmetric_difference_update(self, other):
+ """Update the set, retaining only elements unique to both sets."""
+
+ if not isinstance(other, Set):
+ raise ValueError("other must be a Set instance")
+ if self is other: # lgtm[py/comparison-using-is]
+ self.items.clear()
+ else:
+ overlap = self.intersection(other)
+ self.union_update(other)
+ self.difference_update(overlap)
+
+ def union(self, other):
+ """Return a new set which is the union of ``self`` and ``other``.
+
+ Returns the same Set type as this set.
+ """
+
+ obj = self._clone()
+ obj.union_update(other)
+ return obj
+
+ def intersection(self, other):
+ """Return a new set which is the intersection of ``self`` and
+ ``other``.
+
+ Returns the same Set type as this set.
+ """
+
+ obj = self._clone()
+ obj.intersection_update(other)
+ return obj
+
+ def difference(self, other):
+ """Return a new set which ``self`` - ``other``, i.e. the items
+ in ``self`` which are not also in ``other``.
+
+ Returns the same Set type as this set.
+ """
+
+ obj = self._clone()
+ obj.difference_update(other)
+ return obj
+
+ def symmetric_difference(self, other):
+ """Return a new set which (``self`` - ``other``) | (``other``
+ - ``self), ie: the items in either ``self`` or ``other`` which
+ are not contained in their intersection.
+
+ Returns the same Set type as this set.
+ """
+
+ obj = self._clone()
+ obj.symmetric_difference_update(other)
+ return obj
+
+ def __or__(self, other):
+ return self.union(other)
+
+ def __and__(self, other):
+ return self.intersection(other)
+
+ def __add__(self, other):
+ return self.union(other)
+
+ def __sub__(self, other):
+ return self.difference(other)
+
+ def __xor__(self, other):
+ return self.symmetric_difference(other)
+
+ def __ior__(self, other):
+ self.union_update(other)
+ return self
+
+ def __iand__(self, other):
+ self.intersection_update(other)
+ return self
+
+ def __iadd__(self, other):
+ self.union_update(other)
+ return self
+
+ def __isub__(self, other):
+ self.difference_update(other)
+ return self
+
+ def __ixor__(self, other):
+ self.symmetric_difference_update(other)
+ return self
+
+ def update(self, other):
+ """Update the set, adding any elements from other which are not
+ already in the set.
+
+ *other*, the collection of items with which to update the set, which
+ may be any iterable type.
+ """
+
+ for item in other:
+ self.add(item)
+
+ def clear(self):
+ """Make the set empty."""
+ self.items.clear()
+
+ def __eq__(self, other):
+ return self.items == other.items
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __len__(self):
+ return len(self.items)
+
+ def __iter__(self):
+ return iter(self.items)
+
+ def __getitem__(self, i):
+ if isinstance(i, slice):
+ return list(itertools.islice(self.items, i.start, i.stop, i.step))
+ else:
+ return next(itertools.islice(self.items, i, i + 1))
+
+ def __delitem__(self, i):
+ if isinstance(i, slice):
+ for elt in list(self[i]):
+ del self.items[elt]
+ else:
+ del self.items[self[i]]
+
+ def issubset(self, other):
+ """Is this set a subset of *other*?
+
+ Returns a ``bool``.
+ """
+
+ if not isinstance(other, Set):
+ raise ValueError("other must be a Set instance")
+ for item in self.items:
+ if item not in other.items:
+ return False
+ return True
+
+ def issuperset(self, other):
+ """Is this set a superset of *other*?
+
+ Returns a ``bool``.
+ """
+
+ if not isinstance(other, Set):
+ raise ValueError("other must be a Set instance")
+ for item in other.items:
+ if item not in self.items:
+ return False
+ return True
+
+ def isdisjoint(self, other):
+ if not isinstance(other, Set):
+ raise ValueError("other must be a Set instance")
+ for item in other.items:
+ if item in self.items:
+ return False
+ return True
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tokenizer.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..454cac4a85e609d3429df45cbdfcb4103bd19213
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tokenizer.py
@@ -0,0 +1,708 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""Tokenize DNS zone file format"""
+
+import io
+import sys
+from typing import Any, List, Optional, Tuple
+
+import dns.exception
+import dns.name
+import dns.ttl
+
+_DELIMITERS = {" ", "\t", "\n", ";", "(", ")", '"'}
+_QUOTING_DELIMITERS = {'"'}
+
+EOF = 0
+EOL = 1
+WHITESPACE = 2
+IDENTIFIER = 3
+QUOTED_STRING = 4
+COMMENT = 5
+DELIMITER = 6
+
+
+class UngetBufferFull(dns.exception.DNSException):
+ """An attempt was made to unget a token when the unget buffer was full."""
+
+
+class Token:
+ """A DNS zone file format token.
+
+ ttype: The token type
+ value: The token value
+ has_escape: Does the token value contain escapes?
+ """
+
+ def __init__(
+ self,
+ ttype: int,
+ value: Any = "",
+ has_escape: bool = False,
+ comment: Optional[str] = None,
+ ):
+ """Initialize a token instance."""
+
+ self.ttype = ttype
+ self.value = value
+ self.has_escape = has_escape
+ self.comment = comment
+
+ def is_eof(self) -> bool:
+ return self.ttype == EOF
+
+ def is_eol(self) -> bool:
+ return self.ttype == EOL
+
+ def is_whitespace(self) -> bool:
+ return self.ttype == WHITESPACE
+
+ def is_identifier(self) -> bool:
+ return self.ttype == IDENTIFIER
+
+ def is_quoted_string(self) -> bool:
+ return self.ttype == QUOTED_STRING
+
+ def is_comment(self) -> bool:
+ return self.ttype == COMMENT
+
+ def is_delimiter(self) -> bool: # pragma: no cover (we don't return delimiters yet)
+ return self.ttype == DELIMITER
+
+ def is_eol_or_eof(self) -> bool:
+ return self.ttype == EOL or self.ttype == EOF
+
+ def __eq__(self, other):
+ if not isinstance(other, Token):
+ return False
+ return self.ttype == other.ttype and self.value == other.value
+
+ def __ne__(self, other):
+ if not isinstance(other, Token):
+ return True
+ return self.ttype != other.ttype or self.value != other.value
+
+ def __str__(self):
+ return '%d "%s"' % (self.ttype, self.value)
+
+ def unescape(self) -> "Token":
+ if not self.has_escape:
+ return self
+ unescaped = ""
+ l = len(self.value)
+ i = 0
+ while i < l:
+ c = self.value[i]
+ i += 1
+ if c == "\\":
+ if i >= l: # pragma: no cover (can't happen via get())
+ raise dns.exception.UnexpectedEnd
+ c = self.value[i]
+ i += 1
+ if c.isdigit():
+ if i >= l:
+ raise dns.exception.UnexpectedEnd
+ c2 = self.value[i]
+ i += 1
+ if i >= l:
+ raise dns.exception.UnexpectedEnd
+ c3 = self.value[i]
+ i += 1
+ if not (c2.isdigit() and c3.isdigit()):
+ raise dns.exception.SyntaxError
+ codepoint = int(c) * 100 + int(c2) * 10 + int(c3)
+ if codepoint > 255:
+ raise dns.exception.SyntaxError
+ c = chr(codepoint)
+ unescaped += c
+ return Token(self.ttype, unescaped)
+
+ def unescape_to_bytes(self) -> "Token":
+ # We used to use unescape() for TXT-like records, but this
+ # caused problems as we'd process DNS escapes into Unicode code
+ # points instead of byte values, and then a to_text() of the
+ # processed data would not equal the original input. For
+ # example, \226 in the TXT record would have a to_text() of
+ # \195\162 because we applied UTF-8 encoding to Unicode code
+ # point 226.
+ #
+ # We now apply escapes while converting directly to bytes,
+ # avoiding this double encoding.
+ #
+ # This code also handles cases where the unicode input has
+ # non-ASCII code-points in it by converting it to UTF-8. TXT
+ # records aren't defined for Unicode, but this is the best we
+ # can do to preserve meaning. For example,
+ #
+ # foo\u200bbar
+ #
+ # (where \u200b is Unicode code point 0x200b) will be treated
+ # as if the input had been the UTF-8 encoding of that string,
+ # namely:
+ #
+ # foo\226\128\139bar
+ #
+ unescaped = b""
+ l = len(self.value)
+ i = 0
+ while i < l:
+ c = self.value[i]
+ i += 1
+ if c == "\\":
+ if i >= l: # pragma: no cover (can't happen via get())
+ raise dns.exception.UnexpectedEnd
+ c = self.value[i]
+ i += 1
+ if c.isdigit():
+ if i >= l:
+ raise dns.exception.UnexpectedEnd
+ c2 = self.value[i]
+ i += 1
+ if i >= l:
+ raise dns.exception.UnexpectedEnd
+ c3 = self.value[i]
+ i += 1
+ if not (c2.isdigit() and c3.isdigit()):
+ raise dns.exception.SyntaxError
+ codepoint = int(c) * 100 + int(c2) * 10 + int(c3)
+ if codepoint > 255:
+ raise dns.exception.SyntaxError
+ unescaped += b"%c" % (codepoint)
+ else:
+ # Note that as mentioned above, if c is a Unicode
+ # code point outside of the ASCII range, then this
+ # += is converting that code point to its UTF-8
+ # encoding and appending multiple bytes to
+ # unescaped.
+ unescaped += c.encode()
+ else:
+ unescaped += c.encode()
+ return Token(self.ttype, bytes(unescaped))
+
+
+class Tokenizer:
+ """A DNS zone file format tokenizer.
+
+ A token object is basically a (type, value) tuple. The valid
+ types are EOF, EOL, WHITESPACE, IDENTIFIER, QUOTED_STRING,
+ COMMENT, and DELIMITER.
+
+ file: The file to tokenize
+
+ ungotten_char: The most recently ungotten character, or None.
+
+ ungotten_token: The most recently ungotten token, or None.
+
+ multiline: The current multiline level. This value is increased
+ by one every time a '(' delimiter is read, and decreased by one every time
+ a ')' delimiter is read.
+
+ quoting: This variable is true if the tokenizer is currently
+ reading a quoted string.
+
+ eof: This variable is true if the tokenizer has encountered EOF.
+
+ delimiters: The current delimiter dictionary.
+
+ line_number: The current line number
+
+ filename: A filename that will be returned by the where() method.
+
+ idna_codec: A dns.name.IDNACodec, specifies the IDNA
+ encoder/decoder. If None, the default IDNA 2003
+ encoder/decoder is used.
+ """
+
+ def __init__(
+ self,
+ f: Any = sys.stdin,
+ filename: Optional[str] = None,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ ):
+ """Initialize a tokenizer instance.
+
+ f: The file to tokenize. The default is sys.stdin.
+ This parameter may also be a string, in which case the tokenizer
+ will take its input from the contents of the string.
+
+ filename: the name of the filename that the where() method
+ will return.
+
+ idna_codec: A dns.name.IDNACodec, specifies the IDNA
+ encoder/decoder. If None, the default IDNA 2003
+ encoder/decoder is used.
+ """
+
+ if isinstance(f, str):
+ f = io.StringIO(f)
+ if filename is None:
+ filename = ""
+ elif isinstance(f, bytes):
+ f = io.StringIO(f.decode())
+ if filename is None:
+ filename = ""
+ else:
+ if filename is None:
+ if f is sys.stdin:
+ filename = ""
+ else:
+ filename = ""
+ self.file = f
+ self.ungotten_char: Optional[str] = None
+ self.ungotten_token: Optional[Token] = None
+ self.multiline = 0
+ self.quoting = False
+ self.eof = False
+ self.delimiters = _DELIMITERS
+ self.line_number = 1
+ assert filename is not None
+ self.filename = filename
+ if idna_codec is None:
+ self.idna_codec: dns.name.IDNACodec = dns.name.IDNA_2003
+ else:
+ self.idna_codec = idna_codec
+
+ def _get_char(self) -> str:
+ """Read a character from input."""
+
+ if self.ungotten_char is None:
+ if self.eof:
+ c = ""
+ else:
+ c = self.file.read(1)
+ if c == "":
+ self.eof = True
+ elif c == "\n":
+ self.line_number += 1
+ else:
+ c = self.ungotten_char
+ self.ungotten_char = None
+ return c
+
+ def where(self) -> Tuple[str, int]:
+ """Return the current location in the input.
+
+ Returns a (string, int) tuple. The first item is the filename of
+ the input, the second is the current line number.
+ """
+
+ return (self.filename, self.line_number)
+
+ def _unget_char(self, c: str) -> None:
+ """Unget a character.
+
+ The unget buffer for characters is only one character large; it is
+ an error to try to unget a character when the unget buffer is not
+ empty.
+
+ c: the character to unget
+ raises UngetBufferFull: there is already an ungotten char
+ """
+
+ if self.ungotten_char is not None:
+ # this should never happen!
+ raise UngetBufferFull # pragma: no cover
+ self.ungotten_char = c
+
+ def skip_whitespace(self) -> int:
+ """Consume input until a non-whitespace character is encountered.
+
+ The non-whitespace character is then ungotten, and the number of
+ whitespace characters consumed is returned.
+
+ If the tokenizer is in multiline mode, then newlines are whitespace.
+
+ Returns the number of characters skipped.
+ """
+
+ skipped = 0
+ while True:
+ c = self._get_char()
+ if c != " " and c != "\t":
+ if (c != "\n") or not self.multiline:
+ self._unget_char(c)
+ return skipped
+ skipped += 1
+
+ def get(self, want_leading: bool = False, want_comment: bool = False) -> Token:
+ """Get the next token.
+
+ want_leading: If True, return a WHITESPACE token if the
+ first character read is whitespace. The default is False.
+
+ want_comment: If True, return a COMMENT token if the
+ first token read is a comment. The default is False.
+
+ Raises dns.exception.UnexpectedEnd: input ended prematurely
+
+ Raises dns.exception.SyntaxError: input was badly formed
+
+ Returns a Token.
+ """
+
+ if self.ungotten_token is not None:
+ utoken = self.ungotten_token
+ self.ungotten_token = None
+ if utoken.is_whitespace():
+ if want_leading:
+ return utoken
+ elif utoken.is_comment():
+ if want_comment:
+ return utoken
+ else:
+ return utoken
+ skipped = self.skip_whitespace()
+ if want_leading and skipped > 0:
+ return Token(WHITESPACE, " ")
+ token = ""
+ ttype = IDENTIFIER
+ has_escape = False
+ while True:
+ c = self._get_char()
+ if c == "" or c in self.delimiters:
+ if c == "" and self.quoting:
+ raise dns.exception.UnexpectedEnd
+ if token == "" and ttype != QUOTED_STRING:
+ if c == "(":
+ self.multiline += 1
+ self.skip_whitespace()
+ continue
+ elif c == ")":
+ if self.multiline <= 0:
+ raise dns.exception.SyntaxError
+ self.multiline -= 1
+ self.skip_whitespace()
+ continue
+ elif c == '"':
+ if not self.quoting:
+ self.quoting = True
+ self.delimiters = _QUOTING_DELIMITERS
+ ttype = QUOTED_STRING
+ continue
+ else:
+ self.quoting = False
+ self.delimiters = _DELIMITERS
+ self.skip_whitespace()
+ continue
+ elif c == "\n":
+ return Token(EOL, "\n")
+ elif c == ";":
+ while 1:
+ c = self._get_char()
+ if c == "\n" or c == "":
+ break
+ token += c
+ if want_comment:
+ self._unget_char(c)
+ return Token(COMMENT, token)
+ elif c == "":
+ if self.multiline:
+ raise dns.exception.SyntaxError(
+ "unbalanced parentheses"
+ )
+ return Token(EOF, comment=token)
+ elif self.multiline:
+ self.skip_whitespace()
+ token = ""
+ continue
+ else:
+ return Token(EOL, "\n", comment=token)
+ else:
+ # This code exists in case we ever want a
+ # delimiter to be returned. It never produces
+ # a token currently.
+ token = c
+ ttype = DELIMITER
+ else:
+ self._unget_char(c)
+ break
+ elif self.quoting and c == "\n":
+ raise dns.exception.SyntaxError("newline in quoted string")
+ elif c == "\\":
+ #
+ # It's an escape. Put it and the next character into
+ # the token; it will be checked later for goodness.
+ #
+ token += c
+ has_escape = True
+ c = self._get_char()
+ if c == "" or (c == "\n" and not self.quoting):
+ raise dns.exception.UnexpectedEnd
+ token += c
+ if token == "" and ttype != QUOTED_STRING:
+ if self.multiline:
+ raise dns.exception.SyntaxError("unbalanced parentheses")
+ ttype = EOF
+ return Token(ttype, token, has_escape)
+
+ def unget(self, token: Token) -> None:
+ """Unget a token.
+
+ The unget buffer for tokens is only one token large; it is
+ an error to try to unget a token when the unget buffer is not
+ empty.
+
+ token: the token to unget
+
+ Raises UngetBufferFull: there is already an ungotten token
+ """
+
+ if self.ungotten_token is not None:
+ raise UngetBufferFull
+ self.ungotten_token = token
+
+ def next(self):
+ """Return the next item in an iteration.
+
+ Returns a Token.
+ """
+
+ token = self.get()
+ if token.is_eof():
+ raise StopIteration
+ return token
+
+ __next__ = next
+
+ def __iter__(self):
+ return self
+
+ # Helpers
+
+ def get_int(self, base: int = 10) -> int:
+ """Read the next token and interpret it as an unsigned integer.
+
+ Raises dns.exception.SyntaxError if not an unsigned integer.
+
+ Returns an int.
+ """
+
+ token = self.get().unescape()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError("expecting an identifier")
+ if not token.value.isdigit():
+ raise dns.exception.SyntaxError("expecting an integer")
+ return int(token.value, base)
+
+ def get_uint8(self) -> int:
+ """Read the next token and interpret it as an 8-bit unsigned
+ integer.
+
+ Raises dns.exception.SyntaxError if not an 8-bit unsigned integer.
+
+ Returns an int.
+ """
+
+ value = self.get_int()
+ if value < 0 or value > 255:
+ raise dns.exception.SyntaxError(
+ "%d is not an unsigned 8-bit integer" % value
+ )
+ return value
+
+ def get_uint16(self, base: int = 10) -> int:
+ """Read the next token and interpret it as a 16-bit unsigned
+ integer.
+
+ Raises dns.exception.SyntaxError if not a 16-bit unsigned integer.
+
+ Returns an int.
+ """
+
+ value = self.get_int(base=base)
+ if value < 0 or value > 65535:
+ if base == 8:
+ raise dns.exception.SyntaxError(
+ "%o is not an octal unsigned 16-bit integer" % value
+ )
+ else:
+ raise dns.exception.SyntaxError(
+ "%d is not an unsigned 16-bit integer" % value
+ )
+ return value
+
+ def get_uint32(self, base: int = 10) -> int:
+ """Read the next token and interpret it as a 32-bit unsigned
+ integer.
+
+ Raises dns.exception.SyntaxError if not a 32-bit unsigned integer.
+
+ Returns an int.
+ """
+
+ value = self.get_int(base=base)
+ if value < 0 or value > 4294967295:
+ raise dns.exception.SyntaxError(
+ "%d is not an unsigned 32-bit integer" % value
+ )
+ return value
+
+ def get_uint48(self, base: int = 10) -> int:
+ """Read the next token and interpret it as a 48-bit unsigned
+ integer.
+
+ Raises dns.exception.SyntaxError if not a 48-bit unsigned integer.
+
+ Returns an int.
+ """
+
+ value = self.get_int(base=base)
+ if value < 0 or value > 281474976710655:
+ raise dns.exception.SyntaxError(
+ "%d is not an unsigned 48-bit integer" % value
+ )
+ return value
+
+ def get_string(self, max_length: Optional[int] = None) -> str:
+ """Read the next token and interpret it as a string.
+
+ Raises dns.exception.SyntaxError if not a string.
+ Raises dns.exception.SyntaxError if token value length
+ exceeds max_length (if specified).
+
+ Returns a string.
+ """
+
+ token = self.get().unescape()
+ if not (token.is_identifier() or token.is_quoted_string()):
+ raise dns.exception.SyntaxError("expecting a string")
+ if max_length and len(token.value) > max_length:
+ raise dns.exception.SyntaxError("string too long")
+ return token.value
+
+ def get_identifier(self) -> str:
+ """Read the next token, which should be an identifier.
+
+ Raises dns.exception.SyntaxError if not an identifier.
+
+ Returns a string.
+ """
+
+ token = self.get().unescape()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError("expecting an identifier")
+ return token.value
+
+ def get_remaining(self, max_tokens: Optional[int] = None) -> List[Token]:
+ """Return the remaining tokens on the line, until an EOL or EOF is seen.
+
+ max_tokens: If not None, stop after this number of tokens.
+
+ Returns a list of tokens.
+ """
+
+ tokens = []
+ while True:
+ token = self.get()
+ if token.is_eol_or_eof():
+ self.unget(token)
+ break
+ tokens.append(token)
+ if len(tokens) == max_tokens:
+ break
+ return tokens
+
+ def concatenate_remaining_identifiers(self, allow_empty: bool = False) -> str:
+ """Read the remaining tokens on the line, which should be identifiers.
+
+ Raises dns.exception.SyntaxError if there are no remaining tokens,
+ unless `allow_empty=True` is given.
+
+ Raises dns.exception.SyntaxError if a token is seen that is not an
+ identifier.
+
+ Returns a string containing a concatenation of the remaining
+ identifiers.
+ """
+ s = ""
+ while True:
+ token = self.get().unescape()
+ if token.is_eol_or_eof():
+ self.unget(token)
+ break
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ s += token.value
+ if not (allow_empty or s):
+ raise dns.exception.SyntaxError("expecting another identifier")
+ return s
+
+ def as_name(
+ self,
+ token: Token,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = False,
+ relativize_to: Optional[dns.name.Name] = None,
+ ) -> dns.name.Name:
+ """Try to interpret the token as a DNS name.
+
+ Raises dns.exception.SyntaxError if not a name.
+
+ Returns a dns.name.Name.
+ """
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError("expecting an identifier")
+ name = dns.name.from_text(token.value, origin, self.idna_codec)
+ return name.choose_relativity(relativize_to or origin, relativize)
+
+ def get_name(
+ self,
+ origin: Optional[dns.name.Name] = None,
+ relativize: bool = False,
+ relativize_to: Optional[dns.name.Name] = None,
+ ) -> dns.name.Name:
+ """Read the next token and interpret it as a DNS name.
+
+ Raises dns.exception.SyntaxError if not a name.
+
+ Returns a dns.name.Name.
+ """
+
+ token = self.get()
+ return self.as_name(token, origin, relativize, relativize_to)
+
+ def get_eol_as_token(self) -> Token:
+ """Read the next token and raise an exception if it isn't EOL or
+ EOF.
+
+ Returns a string.
+ """
+
+ token = self.get()
+ if not token.is_eol_or_eof():
+ raise dns.exception.SyntaxError(
+ 'expected EOL or EOF, got %d "%s"' % (token.ttype, token.value)
+ )
+ return token
+
+ def get_eol(self) -> str:
+ return self.get_eol_as_token().value
+
+ def get_ttl(self) -> int:
+ """Read the next token and interpret it as a DNS TTL.
+
+ Raises dns.exception.SyntaxError or dns.ttl.BadTTL if not an
+ identifier or badly formed.
+
+ Returns an int.
+ """
+
+ token = self.get().unescape()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError("expecting an identifier")
+ return dns.ttl.from_text(token.value)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/transaction.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/transaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..84e54f7d548d95fdfc0c6657f5ec6549f43d18c5
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/transaction.py
@@ -0,0 +1,651 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+import collections
+from typing import Any, Callable, Iterator, List, Optional, Tuple, Union
+
+import dns.exception
+import dns.name
+import dns.node
+import dns.rdataclass
+import dns.rdataset
+import dns.rdatatype
+import dns.rrset
+import dns.serial
+import dns.ttl
+
+
+class TransactionManager:
+ def reader(self) -> "Transaction":
+ """Begin a read-only transaction."""
+ raise NotImplementedError # pragma: no cover
+
+ def writer(self, replacement: bool = False) -> "Transaction":
+ """Begin a writable transaction.
+
+ *replacement*, a ``bool``. If `True`, the content of the
+ transaction completely replaces any prior content. If False,
+ the default, then the content of the transaction updates the
+ existing content.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def origin_information(
+ self,
+ ) -> Tuple[Optional[dns.name.Name], bool, Optional[dns.name.Name]]:
+ """Returns a tuple
+
+ (absolute_origin, relativize, effective_origin)
+
+ giving the absolute name of the default origin for any
+ relative domain names, the "effective origin", and whether
+ names should be relativized. The "effective origin" is the
+ absolute origin if relativize is False, and the empty name if
+ relativize is true. (The effective origin is provided even
+ though it can be computed from the absolute_origin and
+ relativize setting because it avoids a lot of code
+ duplication.)
+
+ If the returned names are `None`, then no origin information is
+ available.
+
+ This information is used by code working with transactions to
+ allow it to coordinate relativization. The transaction code
+ itself takes what it gets (i.e. does not change name
+ relativity).
+
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def get_class(self) -> dns.rdataclass.RdataClass:
+ """The class of the transaction manager."""
+ raise NotImplementedError # pragma: no cover
+
+ def from_wire_origin(self) -> Optional[dns.name.Name]:
+ """Origin to use in from_wire() calls."""
+ (absolute_origin, relativize, _) = self.origin_information()
+ if relativize:
+ return absolute_origin
+ else:
+ return None
+
+
+class DeleteNotExact(dns.exception.DNSException):
+ """Existing data did not match data specified by an exact delete."""
+
+
+class ReadOnly(dns.exception.DNSException):
+ """Tried to write to a read-only transaction."""
+
+
+class AlreadyEnded(dns.exception.DNSException):
+ """Tried to use an already-ended transaction."""
+
+
+def _ensure_immutable_rdataset(rdataset):
+ if rdataset is None or isinstance(rdataset, dns.rdataset.ImmutableRdataset):
+ return rdataset
+ return dns.rdataset.ImmutableRdataset(rdataset)
+
+
+def _ensure_immutable_node(node):
+ if node is None or node.is_immutable():
+ return node
+ return dns.node.ImmutableNode(node)
+
+
+CheckPutRdatasetType = Callable[
+ ["Transaction", dns.name.Name, dns.rdataset.Rdataset], None
+]
+CheckDeleteRdatasetType = Callable[
+ ["Transaction", dns.name.Name, dns.rdatatype.RdataType, dns.rdatatype.RdataType],
+ None,
+]
+CheckDeleteNameType = Callable[["Transaction", dns.name.Name], None]
+
+
+class Transaction:
+ def __init__(
+ self,
+ manager: TransactionManager,
+ replacement: bool = False,
+ read_only: bool = False,
+ ):
+ self.manager = manager
+ self.replacement = replacement
+ self.read_only = read_only
+ self._ended = False
+ self._check_put_rdataset: List[CheckPutRdatasetType] = []
+ self._check_delete_rdataset: List[CheckDeleteRdatasetType] = []
+ self._check_delete_name: List[CheckDeleteNameType] = []
+
+ #
+ # This is the high level API
+ #
+ # Note that we currently use non-immutable types in the return type signature to
+ # avoid covariance problems, e.g. if the caller has a List[Rdataset], mypy will be
+ # unhappy if we return an ImmutableRdataset.
+
+ def get(
+ self,
+ name: Optional[Union[dns.name.Name, str]],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ ) -> dns.rdataset.Rdataset:
+ """Return the rdataset associated with *name*, *rdtype*, and *covers*,
+ or `None` if not found.
+
+ Note that the returned rdataset is immutable.
+ """
+ self._check_ended()
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ covers = dns.rdatatype.RdataType.make(covers)
+ rdataset = self._get_rdataset(name, rdtype, covers)
+ return _ensure_immutable_rdataset(rdataset)
+
+ def get_node(self, name: dns.name.Name) -> Optional[dns.node.Node]:
+ """Return the node at *name*, if any.
+
+ Returns an immutable node or ``None``.
+ """
+ return _ensure_immutable_node(self._get_node(name))
+
+ def _check_read_only(self) -> None:
+ if self.read_only:
+ raise ReadOnly
+
+ def add(self, *args: Any) -> None:
+ """Add records.
+
+ The arguments may be:
+
+ - rrset
+
+ - name, rdataset...
+
+ - name, ttl, rdata...
+ """
+ self._check_ended()
+ self._check_read_only()
+ self._add(False, args)
+
+ def replace(self, *args: Any) -> None:
+ """Replace the existing rdataset at the name with the specified
+ rdataset, or add the specified rdataset if there was no existing
+ rdataset.
+
+ The arguments may be:
+
+ - rrset
+
+ - name, rdataset...
+
+ - name, ttl, rdata...
+
+ Note that if you want to replace the entire node, you should do
+ a delete of the name followed by one or more calls to add() or
+ replace().
+ """
+ self._check_ended()
+ self._check_read_only()
+ self._add(True, args)
+
+ def delete(self, *args: Any) -> None:
+ """Delete records.
+
+ It is not an error if some of the records are not in the existing
+ set.
+
+ The arguments may be:
+
+ - rrset
+
+ - name
+
+ - name, rdatatype, [covers]
+
+ - name, rdataset...
+
+ - name, rdata...
+ """
+ self._check_ended()
+ self._check_read_only()
+ self._delete(False, args)
+
+ def delete_exact(self, *args: Any) -> None:
+ """Delete records.
+
+ The arguments may be:
+
+ - rrset
+
+ - name
+
+ - name, rdatatype, [covers]
+
+ - name, rdataset...
+
+ - name, rdata...
+
+ Raises dns.transaction.DeleteNotExact if some of the records
+ are not in the existing set.
+
+ """
+ self._check_ended()
+ self._check_read_only()
+ self._delete(True, args)
+
+ def name_exists(self, name: Union[dns.name.Name, str]) -> bool:
+ """Does the specified name exist?"""
+ self._check_ended()
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ return self._name_exists(name)
+
+ def update_serial(
+ self,
+ value: int = 1,
+ relative: bool = True,
+ name: dns.name.Name = dns.name.empty,
+ ) -> None:
+ """Update the serial number.
+
+ *value*, an `int`, is an increment if *relative* is `True`, or the
+ actual value to set if *relative* is `False`.
+
+ Raises `KeyError` if there is no SOA rdataset at *name*.
+
+ Raises `ValueError` if *value* is negative or if the increment is
+ so large that it would cause the new serial to be less than the
+ prior value.
+ """
+ self._check_ended()
+ if value < 0:
+ raise ValueError("negative update_serial() value")
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ rdataset = self._get_rdataset(name, dns.rdatatype.SOA, dns.rdatatype.NONE)
+ if rdataset is None or len(rdataset) == 0:
+ raise KeyError
+ if relative:
+ serial = dns.serial.Serial(rdataset[0].serial) + value
+ else:
+ serial = dns.serial.Serial(value)
+ serial = serial.value # convert back to int
+ if serial == 0:
+ serial = 1
+ rdata = rdataset[0].replace(serial=serial)
+ new_rdataset = dns.rdataset.from_rdata(rdataset.ttl, rdata)
+ self.replace(name, new_rdataset)
+
+ def __iter__(self):
+ self._check_ended()
+ return self._iterate_rdatasets()
+
+ def changed(self) -> bool:
+ """Has this transaction changed anything?
+
+ For read-only transactions, the result is always `False`.
+
+ For writable transactions, the result is `True` if at some time
+ during the life of the transaction, the content was changed.
+ """
+ self._check_ended()
+ return self._changed()
+
+ def commit(self) -> None:
+ """Commit the transaction.
+
+ Normally transactions are used as context managers and commit
+ or rollback automatically, but it may be done explicitly if needed.
+ A ``dns.transaction.Ended`` exception will be raised if you try
+ to use a transaction after it has been committed or rolled back.
+
+ Raises an exception if the commit fails (in which case the transaction
+ is also rolled back.
+ """
+ self._end(True)
+
+ def rollback(self) -> None:
+ """Rollback the transaction.
+
+ Normally transactions are used as context managers and commit
+ or rollback automatically, but it may be done explicitly if needed.
+ A ``dns.transaction.AlreadyEnded`` exception will be raised if you try
+ to use a transaction after it has been committed or rolled back.
+
+ Rollback cannot otherwise fail.
+ """
+ self._end(False)
+
+ def check_put_rdataset(self, check: CheckPutRdatasetType) -> None:
+ """Call *check* before putting (storing) an rdataset.
+
+ The function is called with the transaction, the name, and the rdataset.
+
+ The check function may safely make non-mutating transaction method
+ calls, but behavior is undefined if mutating transaction methods are
+ called. The check function should raise an exception if it objects to
+ the put, and otherwise should return ``None``.
+ """
+ self._check_put_rdataset.append(check)
+
+ def check_delete_rdataset(self, check: CheckDeleteRdatasetType) -> None:
+ """Call *check* before deleting an rdataset.
+
+ The function is called with the transaction, the name, the rdatatype,
+ and the covered rdatatype.
+
+ The check function may safely make non-mutating transaction method
+ calls, but behavior is undefined if mutating transaction methods are
+ called. The check function should raise an exception if it objects to
+ the put, and otherwise should return ``None``.
+ """
+ self._check_delete_rdataset.append(check)
+
+ def check_delete_name(self, check: CheckDeleteNameType) -> None:
+ """Call *check* before putting (storing) an rdataset.
+
+ The function is called with the transaction and the name.
+
+ The check function may safely make non-mutating transaction method
+ calls, but behavior is undefined if mutating transaction methods are
+ called. The check function should raise an exception if it objects to
+ the put, and otherwise should return ``None``.
+ """
+ self._check_delete_name.append(check)
+
+ def iterate_rdatasets(
+ self,
+ ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]:
+ """Iterate all the rdatasets in the transaction, returning
+ (`dns.name.Name`, `dns.rdataset.Rdataset`) tuples.
+
+ Note that as is usual with python iterators, adding or removing items
+ while iterating will invalidate the iterator and may raise `RuntimeError`
+ or fail to iterate over all entries."""
+ self._check_ended()
+ return self._iterate_rdatasets()
+
+ def iterate_names(self) -> Iterator[dns.name.Name]:
+ """Iterate all the names in the transaction.
+
+ Note that as is usual with python iterators, adding or removing names
+ while iterating will invalidate the iterator and may raise `RuntimeError`
+ or fail to iterate over all entries."""
+ self._check_ended()
+ return self._iterate_names()
+
+ #
+ # Helper methods
+ #
+
+ def _raise_if_not_empty(self, method, args):
+ if len(args) != 0:
+ raise TypeError(f"extra parameters to {method}")
+
+ def _rdataset_from_args(self, method, deleting, args):
+ try:
+ arg = args.popleft()
+ if isinstance(arg, dns.rrset.RRset):
+ rdataset = arg.to_rdataset()
+ elif isinstance(arg, dns.rdataset.Rdataset):
+ rdataset = arg
+ else:
+ if deleting:
+ ttl = 0
+ else:
+ if isinstance(arg, int):
+ ttl = arg
+ if ttl > dns.ttl.MAX_TTL:
+ raise ValueError(f"{method}: TTL value too big")
+ else:
+ raise TypeError(f"{method}: expected a TTL")
+ arg = args.popleft()
+ if isinstance(arg, dns.rdata.Rdata):
+ rdataset = dns.rdataset.from_rdata(ttl, arg)
+ else:
+ raise TypeError(f"{method}: expected an Rdata")
+ return rdataset
+ except IndexError:
+ if deleting:
+ return None
+ else:
+ # reraise
+ raise TypeError(f"{method}: expected more arguments")
+
+ def _add(self, replace, args):
+ try:
+ args = collections.deque(args)
+ if replace:
+ method = "replace()"
+ else:
+ method = "add()"
+ arg = args.popleft()
+ if isinstance(arg, str):
+ arg = dns.name.from_text(arg, None)
+ if isinstance(arg, dns.name.Name):
+ name = arg
+ rdataset = self._rdataset_from_args(method, False, args)
+ elif isinstance(arg, dns.rrset.RRset):
+ rrset = arg
+ name = rrset.name
+ # rrsets are also rdatasets, but they don't print the
+ # same and can't be stored in nodes, so convert.
+ rdataset = rrset.to_rdataset()
+ else:
+ raise TypeError(
+ f"{method} requires a name or RRset as the first argument"
+ )
+ if rdataset.rdclass != self.manager.get_class():
+ raise ValueError(f"{method} has objects of wrong RdataClass")
+ if rdataset.rdtype == dns.rdatatype.SOA:
+ (_, _, origin) = self._origin_information()
+ if name != origin:
+ raise ValueError(f"{method} has non-origin SOA")
+ self._raise_if_not_empty(method, args)
+ if not replace:
+ existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers)
+ if existing is not None:
+ if isinstance(existing, dns.rdataset.ImmutableRdataset):
+ trds = dns.rdataset.Rdataset(
+ existing.rdclass, existing.rdtype, existing.covers
+ )
+ trds.update(existing)
+ existing = trds
+ rdataset = existing.union(rdataset)
+ self._checked_put_rdataset(name, rdataset)
+ except IndexError:
+ raise TypeError(f"not enough parameters to {method}")
+
+ def _delete(self, exact, args):
+ try:
+ args = collections.deque(args)
+ if exact:
+ method = "delete_exact()"
+ else:
+ method = "delete()"
+ arg = args.popleft()
+ if isinstance(arg, str):
+ arg = dns.name.from_text(arg, None)
+ if isinstance(arg, dns.name.Name):
+ name = arg
+ if len(args) > 0 and (
+ isinstance(args[0], int) or isinstance(args[0], str)
+ ):
+ # deleting by type and (optionally) covers
+ rdtype = dns.rdatatype.RdataType.make(args.popleft())
+ if len(args) > 0:
+ covers = dns.rdatatype.RdataType.make(args.popleft())
+ else:
+ covers = dns.rdatatype.NONE
+ self._raise_if_not_empty(method, args)
+ existing = self._get_rdataset(name, rdtype, covers)
+ if existing is None:
+ if exact:
+ raise DeleteNotExact(f"{method}: missing rdataset")
+ else:
+ self._delete_rdataset(name, rdtype, covers)
+ return
+ else:
+ rdataset = self._rdataset_from_args(method, True, args)
+ elif isinstance(arg, dns.rrset.RRset):
+ rdataset = arg # rrsets are also rdatasets
+ name = rdataset.name
+ else:
+ raise TypeError(
+ f"{method} requires a name or RRset as the first argument"
+ )
+ self._raise_if_not_empty(method, args)
+ if rdataset:
+ if rdataset.rdclass != self.manager.get_class():
+ raise ValueError(f"{method} has objects of wrong RdataClass")
+ existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers)
+ if existing is not None:
+ if exact:
+ intersection = existing.intersection(rdataset)
+ if intersection != rdataset:
+ raise DeleteNotExact(f"{method}: missing rdatas")
+ rdataset = existing.difference(rdataset)
+ if len(rdataset) == 0:
+ self._checked_delete_rdataset(
+ name, rdataset.rdtype, rdataset.covers
+ )
+ else:
+ self._checked_put_rdataset(name, rdataset)
+ elif exact:
+ raise DeleteNotExact(f"{method}: missing rdataset")
+ else:
+ if exact and not self._name_exists(name):
+ raise DeleteNotExact(f"{method}: name not known")
+ self._checked_delete_name(name)
+ except IndexError:
+ raise TypeError(f"not enough parameters to {method}")
+
+ def _check_ended(self):
+ if self._ended:
+ raise AlreadyEnded
+
+ def _end(self, commit):
+ self._check_ended()
+ if self._ended:
+ raise AlreadyEnded
+ try:
+ self._end_transaction(commit)
+ finally:
+ self._ended = True
+
+ def _checked_put_rdataset(self, name, rdataset):
+ for check in self._check_put_rdataset:
+ check(self, name, rdataset)
+ self._put_rdataset(name, rdataset)
+
+ def _checked_delete_rdataset(self, name, rdtype, covers):
+ for check in self._check_delete_rdataset:
+ check(self, name, rdtype, covers)
+ self._delete_rdataset(name, rdtype, covers)
+
+ def _checked_delete_name(self, name):
+ for check in self._check_delete_name:
+ check(self, name)
+ self._delete_name(name)
+
+ #
+ # Transactions are context managers.
+ #
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if not self._ended:
+ if exc_type is None:
+ self.commit()
+ else:
+ self.rollback()
+ return False
+
+ #
+ # This is the low level API, which must be implemented by subclasses
+ # of Transaction.
+ #
+
+ def _get_rdataset(self, name, rdtype, covers):
+ """Return the rdataset associated with *name*, *rdtype*, and *covers*,
+ or `None` if not found.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def _put_rdataset(self, name, rdataset):
+ """Store the rdataset."""
+ raise NotImplementedError # pragma: no cover
+
+ def _delete_name(self, name):
+ """Delete all data associated with *name*.
+
+ It is not an error if the name does not exist.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def _delete_rdataset(self, name, rdtype, covers):
+ """Delete all data associated with *name*, *rdtype*, and *covers*.
+
+ It is not an error if the rdataset does not exist.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def _name_exists(self, name):
+ """Does name exist?
+
+ Returns a bool.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def _changed(self):
+ """Has this transaction changed anything?"""
+ raise NotImplementedError # pragma: no cover
+
+ def _end_transaction(self, commit):
+ """End the transaction.
+
+ *commit*, a bool. If ``True``, commit the transaction, otherwise
+ roll it back.
+
+ If committing and the commit fails, then roll back and raise an
+ exception.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def _set_origin(self, origin):
+ """Set the origin.
+
+ This method is called when reading a possibly relativized
+ source, and an origin setting operation occurs (e.g. $ORIGIN
+ in a zone file).
+ """
+ raise NotImplementedError # pragma: no cover
+
+ def _iterate_rdatasets(self):
+ """Return an iterator that yields (name, rdataset) tuples."""
+ raise NotImplementedError # pragma: no cover
+
+ def _iterate_names(self):
+ """Return an iterator that yields a name."""
+ raise NotImplementedError # pragma: no cover
+
+ def _get_node(self, name):
+ """Return the node at *name*, if any.
+
+ Returns a node or ``None``.
+ """
+ raise NotImplementedError # pragma: no cover
+
+ #
+ # Low-level API with a default implementation, in case a subclass needs
+ # to override.
+ #
+
+ def _origin_information(self):
+ # This is only used by _add()
+ return self.manager.origin_information()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tsig.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tsig.py
new file mode 100644
index 0000000000000000000000000000000000000000..780852e8e35028f57e2e1e9cd2ebff8f877e0c22
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tsig.py
@@ -0,0 +1,352 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS TSIG support."""
+
+import base64
+import hashlib
+import hmac
+import struct
+
+import dns.exception
+import dns.name
+import dns.rcode
+import dns.rdataclass
+
+
+class BadTime(dns.exception.DNSException):
+ """The current time is not within the TSIG's validity time."""
+
+
+class BadSignature(dns.exception.DNSException):
+ """The TSIG signature fails to verify."""
+
+
+class BadKey(dns.exception.DNSException):
+ """The TSIG record owner name does not match the key."""
+
+
+class BadAlgorithm(dns.exception.DNSException):
+ """The TSIG algorithm does not match the key."""
+
+
+class PeerError(dns.exception.DNSException):
+ """Base class for all TSIG errors generated by the remote peer"""
+
+
+class PeerBadKey(PeerError):
+ """The peer didn't know the key we used"""
+
+
+class PeerBadSignature(PeerError):
+ """The peer didn't like the signature we sent"""
+
+
+class PeerBadTime(PeerError):
+ """The peer didn't like the time we sent"""
+
+
+class PeerBadTruncation(PeerError):
+ """The peer didn't like amount of truncation in the TSIG we sent"""
+
+
+# TSIG Algorithms
+
+HMAC_MD5 = dns.name.from_text("HMAC-MD5.SIG-ALG.REG.INT")
+HMAC_SHA1 = dns.name.from_text("hmac-sha1")
+HMAC_SHA224 = dns.name.from_text("hmac-sha224")
+HMAC_SHA256 = dns.name.from_text("hmac-sha256")
+HMAC_SHA256_128 = dns.name.from_text("hmac-sha256-128")
+HMAC_SHA384 = dns.name.from_text("hmac-sha384")
+HMAC_SHA384_192 = dns.name.from_text("hmac-sha384-192")
+HMAC_SHA512 = dns.name.from_text("hmac-sha512")
+HMAC_SHA512_256 = dns.name.from_text("hmac-sha512-256")
+GSS_TSIG = dns.name.from_text("gss-tsig")
+
+default_algorithm = HMAC_SHA256
+
+mac_sizes = {
+ HMAC_SHA1: 20,
+ HMAC_SHA224: 28,
+ HMAC_SHA256: 32,
+ HMAC_SHA256_128: 16,
+ HMAC_SHA384: 48,
+ HMAC_SHA384_192: 24,
+ HMAC_SHA512: 64,
+ HMAC_SHA512_256: 32,
+ HMAC_MD5: 16,
+ GSS_TSIG: 128, # This is what we assume to be the worst case!
+}
+
+
+class GSSTSig:
+ """
+ GSS-TSIG TSIG implementation. This uses the GSS-API context established
+ in the TKEY message handshake to sign messages using GSS-API message
+ integrity codes, per the RFC.
+
+ In order to avoid a direct GSSAPI dependency, the keyring holds a ref
+ to the GSSAPI object required, rather than the key itself.
+ """
+
+ def __init__(self, gssapi_context):
+ self.gssapi_context = gssapi_context
+ self.data = b""
+ self.name = "gss-tsig"
+
+ def update(self, data):
+ self.data += data
+
+ def sign(self):
+ # defer to the GSSAPI function to sign
+ return self.gssapi_context.get_signature(self.data)
+
+ def verify(self, expected):
+ try:
+ # defer to the GSSAPI function to verify
+ return self.gssapi_context.verify_signature(self.data, expected)
+ except Exception:
+ # note the usage of a bare exception
+ raise BadSignature
+
+
+class GSSTSigAdapter:
+ def __init__(self, keyring):
+ self.keyring = keyring
+
+ def __call__(self, message, keyname):
+ if keyname in self.keyring:
+ key = self.keyring[keyname]
+ if isinstance(key, Key) and key.algorithm == GSS_TSIG:
+ if message:
+ GSSTSigAdapter.parse_tkey_and_step(key, message, keyname)
+ return key
+ else:
+ return None
+
+ @classmethod
+ def parse_tkey_and_step(cls, key, message, keyname):
+ # if the message is a TKEY type, absorb the key material
+ # into the context using step(); this is used to allow the
+ # client to complete the GSSAPI negotiation before attempting
+ # to verify the signed response to a TKEY message exchange
+ try:
+ rrset = message.find_rrset(
+ message.answer, keyname, dns.rdataclass.ANY, dns.rdatatype.TKEY
+ )
+ if rrset:
+ token = rrset[0].key
+ gssapi_context = key.secret
+ return gssapi_context.step(token)
+ except KeyError:
+ pass
+
+
+class HMACTSig:
+ """
+ HMAC TSIG implementation. This uses the HMAC python module to handle the
+ sign/verify operations.
+ """
+
+ _hashes = {
+ HMAC_SHA1: hashlib.sha1,
+ HMAC_SHA224: hashlib.sha224,
+ HMAC_SHA256: hashlib.sha256,
+ HMAC_SHA256_128: (hashlib.sha256, 128),
+ HMAC_SHA384: hashlib.sha384,
+ HMAC_SHA384_192: (hashlib.sha384, 192),
+ HMAC_SHA512: hashlib.sha512,
+ HMAC_SHA512_256: (hashlib.sha512, 256),
+ HMAC_MD5: hashlib.md5,
+ }
+
+ def __init__(self, key, algorithm):
+ try:
+ hashinfo = self._hashes[algorithm]
+ except KeyError:
+ raise NotImplementedError(f"TSIG algorithm {algorithm} is not supported")
+
+ # create the HMAC context
+ if isinstance(hashinfo, tuple):
+ self.hmac_context = hmac.new(key, digestmod=hashinfo[0])
+ self.size = hashinfo[1]
+ else:
+ self.hmac_context = hmac.new(key, digestmod=hashinfo)
+ self.size = None
+ self.name = self.hmac_context.name
+ if self.size:
+ self.name += f"-{self.size}"
+
+ def update(self, data):
+ return self.hmac_context.update(data)
+
+ def sign(self):
+ # defer to the HMAC digest() function for that digestmod
+ digest = self.hmac_context.digest()
+ if self.size:
+ digest = digest[: (self.size // 8)]
+ return digest
+
+ def verify(self, expected):
+ # re-digest and compare the results
+ mac = self.sign()
+ if not hmac.compare_digest(mac, expected):
+ raise BadSignature
+
+
+def _digest(wire, key, rdata, time=None, request_mac=None, ctx=None, multi=None):
+ """Return a context containing the TSIG rdata for the input parameters
+ @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object
+ @raises ValueError: I{other_data} is too long
+ @raises NotImplementedError: I{algorithm} is not supported
+ """
+
+ first = not (ctx and multi)
+ if first:
+ ctx = get_context(key)
+ if request_mac:
+ ctx.update(struct.pack("!H", len(request_mac)))
+ ctx.update(request_mac)
+ ctx.update(struct.pack("!H", rdata.original_id))
+ ctx.update(wire[2:])
+ if first:
+ ctx.update(key.name.to_digestable())
+ ctx.update(struct.pack("!H", dns.rdataclass.ANY))
+ ctx.update(struct.pack("!I", 0))
+ if time is None:
+ time = rdata.time_signed
+ upper_time = (time >> 32) & 0xFFFF
+ lower_time = time & 0xFFFFFFFF
+ time_encoded = struct.pack("!HIH", upper_time, lower_time, rdata.fudge)
+ other_len = len(rdata.other)
+ if other_len > 65535:
+ raise ValueError("TSIG Other Data is > 65535 bytes")
+ if first:
+ ctx.update(key.algorithm.to_digestable() + time_encoded)
+ ctx.update(struct.pack("!HH", rdata.error, other_len) + rdata.other)
+ else:
+ ctx.update(time_encoded)
+ return ctx
+
+
+def _maybe_start_digest(key, mac, multi):
+ """If this is the first message in a multi-message sequence,
+ start a new context.
+ @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object
+ """
+ if multi:
+ ctx = get_context(key)
+ ctx.update(struct.pack("!H", len(mac)))
+ ctx.update(mac)
+ return ctx
+ else:
+ return None
+
+
+def sign(wire, key, rdata, time=None, request_mac=None, ctx=None, multi=False):
+ """Return a (tsig_rdata, mac, ctx) tuple containing the HMAC TSIG rdata
+ for the input parameters, the HMAC MAC calculated by applying the
+ TSIG signature algorithm, and the TSIG digest context.
+ @rtype: (string, dns.tsig.HMACTSig or dns.tsig.GSSTSig object)
+ @raises ValueError: I{other_data} is too long
+ @raises NotImplementedError: I{algorithm} is not supported
+ """
+
+ ctx = _digest(wire, key, rdata, time, request_mac, ctx, multi)
+ mac = ctx.sign()
+ tsig = rdata.replace(time_signed=time, mac=mac)
+
+ return (tsig, _maybe_start_digest(key, mac, multi))
+
+
+def validate(
+ wire, key, owner, rdata, now, request_mac, tsig_start, ctx=None, multi=False
+):
+ """Validate the specified TSIG rdata against the other input parameters.
+
+ @raises FormError: The TSIG is badly formed.
+ @raises BadTime: There is too much time skew between the client and the
+ server.
+ @raises BadSignature: The TSIG signature did not validate
+ @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object"""
+
+ (adcount,) = struct.unpack("!H", wire[10:12])
+ if adcount == 0:
+ raise dns.exception.FormError
+ adcount -= 1
+ new_wire = wire[0:10] + struct.pack("!H", adcount) + wire[12:tsig_start]
+ if rdata.error != 0:
+ if rdata.error == dns.rcode.BADSIG:
+ raise PeerBadSignature
+ elif rdata.error == dns.rcode.BADKEY:
+ raise PeerBadKey
+ elif rdata.error == dns.rcode.BADTIME:
+ raise PeerBadTime
+ elif rdata.error == dns.rcode.BADTRUNC:
+ raise PeerBadTruncation
+ else:
+ raise PeerError("unknown TSIG error code %d" % rdata.error)
+ if abs(rdata.time_signed - now) > rdata.fudge:
+ raise BadTime
+ if key.name != owner:
+ raise BadKey
+ if key.algorithm != rdata.algorithm:
+ raise BadAlgorithm
+ ctx = _digest(new_wire, key, rdata, None, request_mac, ctx, multi)
+ ctx.verify(rdata.mac)
+ return _maybe_start_digest(key, rdata.mac, multi)
+
+
+def get_context(key):
+ """Returns an HMAC context for the specified key.
+
+ @rtype: HMAC context
+ @raises NotImplementedError: I{algorithm} is not supported
+ """
+
+ if key.algorithm == GSS_TSIG:
+ return GSSTSig(key.secret)
+ else:
+ return HMACTSig(key.secret, key.algorithm)
+
+
+class Key:
+ def __init__(self, name, secret, algorithm=default_algorithm):
+ if isinstance(name, str):
+ name = dns.name.from_text(name)
+ self.name = name
+ if isinstance(secret, str):
+ secret = base64.decodebytes(secret.encode())
+ self.secret = secret
+ if isinstance(algorithm, str):
+ algorithm = dns.name.from_text(algorithm)
+ self.algorithm = algorithm
+
+ def __eq__(self, other):
+ return (
+ isinstance(other, Key)
+ and self.name == other.name
+ and self.secret == other.secret
+ and self.algorithm == other.algorithm
+ )
+
+ def __repr__(self):
+ r = f""
+ return r
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tsigkeyring.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tsigkeyring.py
new file mode 100644
index 0000000000000000000000000000000000000000..1010a79f8f3c1856b765fa11e01cb5b6e2f6ea64
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/tsigkeyring.py
@@ -0,0 +1,68 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""A place to store TSIG keys."""
+
+import base64
+from typing import Any, Dict
+
+import dns.name
+import dns.tsig
+
+
+def from_text(textring: Dict[str, Any]) -> Dict[dns.name.Name, dns.tsig.Key]:
+ """Convert a dictionary containing (textual DNS name, base64 secret)
+ pairs into a binary keyring which has (dns.name.Name, bytes) pairs, or
+ a dictionary containing (textual DNS name, (algorithm, base64 secret))
+ pairs into a binary keyring which has (dns.name.Name, dns.tsig.Key) pairs.
+ @rtype: dict"""
+
+ keyring = {}
+ for name, value in textring.items():
+ kname = dns.name.from_text(name)
+ if isinstance(value, str):
+ keyring[kname] = dns.tsig.Key(kname, value).secret
+ else:
+ (algorithm, secret) = value
+ keyring[kname] = dns.tsig.Key(kname, secret, algorithm)
+ return keyring
+
+
+def to_text(keyring: Dict[dns.name.Name, Any]) -> Dict[str, Any]:
+ """Convert a dictionary containing (dns.name.Name, dns.tsig.Key) pairs
+ into a text keyring which has (textual DNS name, (textual algorithm,
+ base64 secret)) pairs, or a dictionary containing (dns.name.Name, bytes)
+ pairs into a text keyring which has (textual DNS name, base64 secret) pairs.
+ @rtype: dict"""
+
+ textring = {}
+
+ def b64encode(secret):
+ return base64.encodebytes(secret).decode().rstrip()
+
+ for name, key in keyring.items():
+ tname = name.to_text()
+ if isinstance(key, bytes):
+ textring[tname] = b64encode(key)
+ else:
+ if isinstance(key.secret, bytes):
+ text_secret = b64encode(key.secret)
+ else:
+ text_secret = str(key.secret)
+
+ textring[tname] = (key.algorithm.to_text(), text_secret)
+ return textring
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ttl.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ttl.py
new file mode 100644
index 0000000000000000000000000000000000000000..264b0338b64e827a2078ebb0edac7daf1a49cd0c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/ttl.py
@@ -0,0 +1,92 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS TTL conversion."""
+
+from typing import Union
+
+import dns.exception
+
+# Technically TTLs are supposed to be between 0 and 2**31 - 1, with values
+# greater than that interpreted as 0, but we do not impose this policy here
+# as values > 2**31 - 1 occur in real world data.
+#
+# We leave it to applications to impose tighter bounds if desired.
+MAX_TTL = 2**32 - 1
+
+
+class BadTTL(dns.exception.SyntaxError):
+ """DNS TTL value is not well-formed."""
+
+
+def from_text(text: str) -> int:
+ """Convert the text form of a TTL to an integer.
+
+ The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.
+
+ *text*, a ``str``, the textual TTL.
+
+ Raises ``dns.ttl.BadTTL`` if the TTL is not well-formed.
+
+ Returns an ``int``.
+ """
+
+ if text.isdigit():
+ total = int(text)
+ elif len(text) == 0:
+ raise BadTTL
+ else:
+ total = 0
+ current = 0
+ need_digit = True
+ for c in text:
+ if c.isdigit():
+ current *= 10
+ current += int(c)
+ need_digit = False
+ else:
+ if need_digit:
+ raise BadTTL
+ c = c.lower()
+ if c == "w":
+ total += current * 604800
+ elif c == "d":
+ total += current * 86400
+ elif c == "h":
+ total += current * 3600
+ elif c == "m":
+ total += current * 60
+ elif c == "s":
+ total += current
+ else:
+ raise BadTTL("unknown unit '%s'" % c)
+ current = 0
+ need_digit = True
+ if not current == 0:
+ raise BadTTL("trailing integer")
+ if total < 0 or total > MAX_TTL:
+ raise BadTTL("TTL should be between 0 and 2**32 - 1 (inclusive)")
+ return total
+
+
+def make(value: Union[int, str]) -> int:
+ if isinstance(value, int):
+ return value
+ elif isinstance(value, str):
+ return dns.ttl.from_text(value)
+ else:
+ raise ValueError("cannot convert value to TTL")
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/update.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/update.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf1157acdfe7f4262afec600fd9a30691aa0f78d
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/update.py
@@ -0,0 +1,386 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Dynamic Update Support"""
+
+from typing import Any, List, Optional, Union
+
+import dns.message
+import dns.name
+import dns.opcode
+import dns.rdata
+import dns.rdataclass
+import dns.rdataset
+import dns.rdatatype
+import dns.tsig
+
+
+class UpdateSection(dns.enum.IntEnum):
+ """Update sections"""
+
+ ZONE = 0
+ PREREQ = 1
+ UPDATE = 2
+ ADDITIONAL = 3
+
+ @classmethod
+ def _maximum(cls):
+ return 3
+
+
+class UpdateMessage(dns.message.Message): # lgtm[py/missing-equals]
+ # ignore the mypy error here as we mean to use a different enum
+ _section_enum = UpdateSection # type: ignore
+
+ def __init__(
+ self,
+ zone: Optional[Union[dns.name.Name, str]] = None,
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ keyring: Optional[Any] = None,
+ keyname: Optional[dns.name.Name] = None,
+ keyalgorithm: Union[dns.name.Name, str] = dns.tsig.default_algorithm,
+ id: Optional[int] = None,
+ ):
+ """Initialize a new DNS Update object.
+
+ See the documentation of the Message class for a complete
+ description of the keyring dictionary.
+
+ *zone*, a ``dns.name.Name``, ``str``, or ``None``, the zone
+ which is being updated. ``None`` should only be used by dnspython's
+ message constructors, as a zone is required for the convenience
+ methods like ``add()``, ``replace()``, etc.
+
+ *rdclass*, an ``int`` or ``str``, the class of the zone.
+
+ The *keyring*, *keyname*, and *keyalgorithm* parameters are passed to
+ ``use_tsig()``; see its documentation for details.
+ """
+ super().__init__(id=id)
+ self.flags |= dns.opcode.to_flags(dns.opcode.UPDATE)
+ if isinstance(zone, str):
+ zone = dns.name.from_text(zone)
+ self.origin = zone
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ self.zone_rdclass = rdclass
+ if self.origin:
+ self.find_rrset(
+ self.zone,
+ self.origin,
+ rdclass,
+ dns.rdatatype.SOA,
+ create=True,
+ force_unique=True,
+ )
+ if keyring is not None:
+ self.use_tsig(keyring, keyname, algorithm=keyalgorithm)
+
+ @property
+ def zone(self) -> List[dns.rrset.RRset]:
+ """The zone section."""
+ return self.sections[0]
+
+ @zone.setter
+ def zone(self, v):
+ self.sections[0] = v
+
+ @property
+ def prerequisite(self) -> List[dns.rrset.RRset]:
+ """The prerequisite section."""
+ return self.sections[1]
+
+ @prerequisite.setter
+ def prerequisite(self, v):
+ self.sections[1] = v
+
+ @property
+ def update(self) -> List[dns.rrset.RRset]:
+ """The update section."""
+ return self.sections[2]
+
+ @update.setter
+ def update(self, v):
+ self.sections[2] = v
+
+ def _add_rr(self, name, ttl, rd, deleting=None, section=None):
+ """Add a single RR to the update section."""
+
+ if section is None:
+ section = self.update
+ covers = rd.covers()
+ rrset = self.find_rrset(
+ section, name, self.zone_rdclass, rd.rdtype, covers, deleting, True, True
+ )
+ rrset.add(rd, ttl)
+
+ def _add(self, replace, section, name, *args):
+ """Add records.
+
+ *replace* is the replacement mode. If ``False``,
+ RRs are added to an existing RRset; if ``True``, the RRset
+ is replaced with the specified contents. The second
+ argument is the section to add to. The third argument
+ is always a name. The other arguments can be:
+
+ - rdataset...
+
+ - ttl, rdata...
+
+ - ttl, rdtype, string...
+ """
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ if isinstance(args[0], dns.rdataset.Rdataset):
+ for rds in args:
+ if replace:
+ self.delete(name, rds.rdtype)
+ for rd in rds:
+ self._add_rr(name, rds.ttl, rd, section=section)
+ else:
+ args = list(args)
+ ttl = int(args.pop(0))
+ if isinstance(args[0], dns.rdata.Rdata):
+ if replace:
+ self.delete(name, args[0].rdtype)
+ for rd in args:
+ self._add_rr(name, ttl, rd, section=section)
+ else:
+ rdtype = dns.rdatatype.RdataType.make(args.pop(0))
+ if replace:
+ self.delete(name, rdtype)
+ for s in args:
+ rd = dns.rdata.from_text(self.zone_rdclass, rdtype, s, self.origin)
+ self._add_rr(name, ttl, rd, section=section)
+
+ def add(self, name: Union[dns.name.Name, str], *args: Any) -> None:
+ """Add records.
+
+ The first argument is always a name. The other
+ arguments can be:
+
+ - rdataset...
+
+ - ttl, rdata...
+
+ - ttl, rdtype, string...
+ """
+
+ self._add(False, self.update, name, *args)
+
+ def delete(self, name: Union[dns.name.Name, str], *args: Any) -> None:
+ """Delete records.
+
+ The first argument is always a name. The other
+ arguments can be:
+
+ - *empty*
+
+ - rdataset...
+
+ - rdata...
+
+ - rdtype, [string...]
+ """
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ if len(args) == 0:
+ self.find_rrset(
+ self.update,
+ name,
+ dns.rdataclass.ANY,
+ dns.rdatatype.ANY,
+ dns.rdatatype.NONE,
+ dns.rdataclass.ANY,
+ True,
+ True,
+ )
+ elif isinstance(args[0], dns.rdataset.Rdataset):
+ for rds in args:
+ for rd in rds:
+ self._add_rr(name, 0, rd, dns.rdataclass.NONE)
+ else:
+ largs = list(args)
+ if isinstance(largs[0], dns.rdata.Rdata):
+ for rd in largs:
+ self._add_rr(name, 0, rd, dns.rdataclass.NONE)
+ else:
+ rdtype = dns.rdatatype.RdataType.make(largs.pop(0))
+ if len(largs) == 0:
+ self.find_rrset(
+ self.update,
+ name,
+ self.zone_rdclass,
+ rdtype,
+ dns.rdatatype.NONE,
+ dns.rdataclass.ANY,
+ True,
+ True,
+ )
+ else:
+ for s in largs:
+ rd = dns.rdata.from_text(
+ self.zone_rdclass,
+ rdtype,
+ s, # type: ignore[arg-type]
+ self.origin,
+ )
+ self._add_rr(name, 0, rd, dns.rdataclass.NONE)
+
+ def replace(self, name: Union[dns.name.Name, str], *args: Any) -> None:
+ """Replace records.
+
+ The first argument is always a name. The other
+ arguments can be:
+
+ - rdataset...
+
+ - ttl, rdata...
+
+ - ttl, rdtype, string...
+
+ Note that if you want to replace the entire node, you should do
+ a delete of the name followed by one or more calls to add.
+ """
+
+ self._add(True, self.update, name, *args)
+
+ def present(self, name: Union[dns.name.Name, str], *args: Any) -> None:
+ """Require that an owner name (and optionally an rdata type,
+ or specific rdataset) exists as a prerequisite to the
+ execution of the update.
+
+ The first argument is always a name.
+ The other arguments can be:
+
+ - rdataset...
+
+ - rdata...
+
+ - rdtype, string...
+ """
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ if len(args) == 0:
+ self.find_rrset(
+ self.prerequisite,
+ name,
+ dns.rdataclass.ANY,
+ dns.rdatatype.ANY,
+ dns.rdatatype.NONE,
+ None,
+ True,
+ True,
+ )
+ elif (
+ isinstance(args[0], dns.rdataset.Rdataset)
+ or isinstance(args[0], dns.rdata.Rdata)
+ or len(args) > 1
+ ):
+ if not isinstance(args[0], dns.rdataset.Rdataset):
+ # Add a 0 TTL
+ largs = list(args)
+ largs.insert(0, 0) # type: ignore[arg-type]
+ self._add(False, self.prerequisite, name, *largs)
+ else:
+ self._add(False, self.prerequisite, name, *args)
+ else:
+ rdtype = dns.rdatatype.RdataType.make(args[0])
+ self.find_rrset(
+ self.prerequisite,
+ name,
+ dns.rdataclass.ANY,
+ rdtype,
+ dns.rdatatype.NONE,
+ None,
+ True,
+ True,
+ )
+
+ def absent(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Optional[Union[dns.rdatatype.RdataType, str]] = None,
+ ) -> None:
+ """Require that an owner name (and optionally an rdata type) does
+ not exist as a prerequisite to the execution of the update."""
+
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ if rdtype is None:
+ self.find_rrset(
+ self.prerequisite,
+ name,
+ dns.rdataclass.NONE,
+ dns.rdatatype.ANY,
+ dns.rdatatype.NONE,
+ None,
+ True,
+ True,
+ )
+ else:
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ self.find_rrset(
+ self.prerequisite,
+ name,
+ dns.rdataclass.NONE,
+ rdtype,
+ dns.rdatatype.NONE,
+ None,
+ True,
+ True,
+ )
+
+ def _get_one_rr_per_rrset(self, value):
+ # Updates are always one_rr_per_rrset
+ return True
+
+ def _parse_rr_header(self, section, name, rdclass, rdtype):
+ deleting = None
+ empty = False
+ if section == UpdateSection.ZONE:
+ if (
+ dns.rdataclass.is_metaclass(rdclass)
+ or rdtype != dns.rdatatype.SOA
+ or self.zone
+ ):
+ raise dns.exception.FormError
+ else:
+ if not self.zone:
+ raise dns.exception.FormError
+ if rdclass in (dns.rdataclass.ANY, dns.rdataclass.NONE):
+ deleting = rdclass
+ rdclass = self.zone[0].rdclass
+ empty = (
+ deleting == dns.rdataclass.ANY or section == UpdateSection.PREREQ
+ )
+ return (rdclass, rdtype, deleting, empty)
+
+
+# backwards compatibility
+Update = UpdateMessage
+
+### BEGIN generated UpdateSection constants
+
+ZONE = UpdateSection.ZONE
+PREREQ = UpdateSection.PREREQ
+UPDATE = UpdateSection.UPDATE
+ADDITIONAL = UpdateSection.ADDITIONAL
+
+### END generated UpdateSection constants
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..251f2583d346fd4b18b52bc11689fd9315dbf087
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/version.py
@@ -0,0 +1,58 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""dnspython release version information."""
+
+#: MAJOR
+MAJOR = 2
+#: MINOR
+MINOR = 6
+#: MICRO
+MICRO = 1
+#: RELEASELEVEL
+RELEASELEVEL = 0x0F
+#: SERIAL
+SERIAL = 0
+
+if RELEASELEVEL == 0x0F: # pragma: no cover lgtm[py/unreachable-statement]
+ #: version
+ version = "%d.%d.%d" % (MAJOR, MINOR, MICRO) # lgtm[py/unreachable-statement]
+elif RELEASELEVEL == 0x00: # pragma: no cover lgtm[py/unreachable-statement]
+ version = "%d.%d.%ddev%d" % (
+ MAJOR,
+ MINOR,
+ MICRO,
+ SERIAL,
+ ) # lgtm[py/unreachable-statement]
+elif RELEASELEVEL == 0x0C: # pragma: no cover lgtm[py/unreachable-statement]
+ version = "%d.%d.%drc%d" % (
+ MAJOR,
+ MINOR,
+ MICRO,
+ SERIAL,
+ ) # lgtm[py/unreachable-statement]
+else: # pragma: no cover lgtm[py/unreachable-statement]
+ version = "%d.%d.%d%x%d" % (
+ MAJOR,
+ MINOR,
+ MICRO,
+ RELEASELEVEL,
+ SERIAL,
+ ) # lgtm[py/unreachable-statement]
+
+#: hexversion
+hexversion = MAJOR << 24 | MINOR << 16 | MICRO << 8 | RELEASELEVEL << 4 | SERIAL
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/versioned.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/versioned.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd78e674e6edbb0dc2dcab6bbc9515b4b2103520
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/versioned.py
@@ -0,0 +1,318 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+"""DNS Versioned Zones."""
+
+import collections
+import threading
+from typing import Callable, Deque, Optional, Set, Union
+
+import dns.exception
+import dns.immutable
+import dns.name
+import dns.node
+import dns.rdataclass
+import dns.rdataset
+import dns.rdatatype
+import dns.rdtypes.ANY.SOA
+import dns.zone
+
+
+class UseTransaction(dns.exception.DNSException):
+ """To alter a versioned zone, use a transaction."""
+
+
+# Backwards compatibility
+Node = dns.zone.VersionedNode
+ImmutableNode = dns.zone.ImmutableVersionedNode
+Version = dns.zone.Version
+WritableVersion = dns.zone.WritableVersion
+ImmutableVersion = dns.zone.ImmutableVersion
+Transaction = dns.zone.Transaction
+
+
+class Zone(dns.zone.Zone): # lgtm[py/missing-equals]
+ __slots__ = [
+ "_versions",
+ "_versions_lock",
+ "_write_txn",
+ "_write_waiters",
+ "_write_event",
+ "_pruning_policy",
+ "_readers",
+ ]
+
+ node_factory = Node
+
+ def __init__(
+ self,
+ origin: Optional[Union[dns.name.Name, str]],
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ relativize: bool = True,
+ pruning_policy: Optional[Callable[["Zone", Version], Optional[bool]]] = None,
+ ):
+ """Initialize a versioned zone object.
+
+ *origin* is the origin of the zone. It may be a ``dns.name.Name``,
+ a ``str``, or ``None``. If ``None``, then the zone's origin will
+ be set by the first ``$ORIGIN`` line in a zone file.
+
+ *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
+
+ *relativize*, a ``bool``, determine's whether domain names are
+ relativized to the zone's origin. The default is ``True``.
+
+ *pruning policy*, a function taking a ``Zone`` and a ``Version`` and returning
+ a ``bool``, or ``None``. Should the version be pruned? If ``None``,
+ the default policy, which retains one version is used.
+ """
+ super().__init__(origin, rdclass, relativize)
+ self._versions: Deque[Version] = collections.deque()
+ self._version_lock = threading.Lock()
+ if pruning_policy is None:
+ self._pruning_policy = self._default_pruning_policy
+ else:
+ self._pruning_policy = pruning_policy
+ self._write_txn: Optional[Transaction] = None
+ self._write_event: Optional[threading.Event] = None
+ self._write_waiters: Deque[threading.Event] = collections.deque()
+ self._readers: Set[Transaction] = set()
+ self._commit_version_unlocked(
+ None, WritableVersion(self, replacement=True), origin
+ )
+
+ def reader(
+ self, id: Optional[int] = None, serial: Optional[int] = None
+ ) -> Transaction: # pylint: disable=arguments-differ
+ if id is not None and serial is not None:
+ raise ValueError("cannot specify both id and serial")
+ with self._version_lock:
+ if id is not None:
+ version = None
+ for v in reversed(self._versions):
+ if v.id == id:
+ version = v
+ break
+ if version is None:
+ raise KeyError("version not found")
+ elif serial is not None:
+ if self.relativize:
+ oname = dns.name.empty
+ else:
+ assert self.origin is not None
+ oname = self.origin
+ version = None
+ for v in reversed(self._versions):
+ n = v.nodes.get(oname)
+ if n:
+ rds = n.get_rdataset(self.rdclass, dns.rdatatype.SOA)
+ if rds and rds[0].serial == serial:
+ version = v
+ break
+ if version is None:
+ raise KeyError("serial not found")
+ else:
+ version = self._versions[-1]
+ txn = Transaction(self, False, version)
+ self._readers.add(txn)
+ return txn
+
+ def writer(self, replacement: bool = False) -> Transaction:
+ event = None
+ while True:
+ with self._version_lock:
+ # Checking event == self._write_event ensures that either
+ # no one was waiting before we got lucky and found no write
+ # txn, or we were the one who was waiting and got woken up.
+ # This prevents "taking cuts" when creating a write txn.
+ if self._write_txn is None and event == self._write_event:
+ # Creating the transaction defers version setup
+ # (i.e. copying the nodes dictionary) until we
+ # give up the lock, so that we hold the lock as
+ # short a time as possible. This is why we call
+ # _setup_version() below.
+ self._write_txn = Transaction(
+ self, replacement, make_immutable=True
+ )
+ # give up our exclusive right to make a Transaction
+ self._write_event = None
+ break
+ # Someone else is writing already, so we will have to
+ # wait, but we want to do the actual wait outside the
+ # lock.
+ event = threading.Event()
+ self._write_waiters.append(event)
+ # wait (note we gave up the lock!)
+ #
+ # We only wake one sleeper at a time, so it's important
+ # that no event waiter can exit this method (e.g. via
+ # cancellation) without returning a transaction or waking
+ # someone else up.
+ #
+ # This is not a problem with Threading module threads as
+ # they cannot be canceled, but could be an issue with trio
+ # tasks when we do the async version of writer().
+ # I.e. we'd need to do something like:
+ #
+ # try:
+ # event.wait()
+ # except trio.Cancelled:
+ # with self._version_lock:
+ # self._maybe_wakeup_one_waiter_unlocked()
+ # raise
+ #
+ event.wait()
+ # Do the deferred version setup.
+ self._write_txn._setup_version()
+ return self._write_txn
+
+ def _maybe_wakeup_one_waiter_unlocked(self):
+ if len(self._write_waiters) > 0:
+ self._write_event = self._write_waiters.popleft()
+ self._write_event.set()
+
+ # pylint: disable=unused-argument
+ def _default_pruning_policy(self, zone, version):
+ return True
+
+ # pylint: enable=unused-argument
+
+ def _prune_versions_unlocked(self):
+ assert len(self._versions) > 0
+ # Don't ever prune a version greater than or equal to one that
+ # a reader has open. This pins versions in memory while the
+ # reader is open, and importantly lets the reader open a txn on
+ # a successor version (e.g. if generating an IXFR).
+ #
+ # Note our definition of least_kept also ensures we do not try to
+ # delete the greatest version.
+ if len(self._readers) > 0:
+ least_kept = min(txn.version.id for txn in self._readers)
+ else:
+ least_kept = self._versions[-1].id
+ while self._versions[0].id < least_kept and self._pruning_policy(
+ self, self._versions[0]
+ ):
+ self._versions.popleft()
+
+ def set_max_versions(self, max_versions: Optional[int]) -> None:
+ """Set a pruning policy that retains up to the specified number
+ of versions
+ """
+ if max_versions is not None and max_versions < 1:
+ raise ValueError("max versions must be at least 1")
+ if max_versions is None:
+
+ def policy(zone, _): # pylint: disable=unused-argument
+ return False
+
+ else:
+
+ def policy(zone, _):
+ return len(zone._versions) > max_versions
+
+ self.set_pruning_policy(policy)
+
+ def set_pruning_policy(
+ self, policy: Optional[Callable[["Zone", Version], Optional[bool]]]
+ ) -> None:
+ """Set the pruning policy for the zone.
+
+ The *policy* function takes a `Version` and returns `True` if
+ the version should be pruned, and `False` otherwise. `None`
+ may also be specified for policy, in which case the default policy
+ is used.
+
+ Pruning checking proceeds from the least version and the first
+ time the function returns `False`, the checking stops. I.e. the
+ retained versions are always a consecutive sequence.
+ """
+ if policy is None:
+ policy = self._default_pruning_policy
+ with self._version_lock:
+ self._pruning_policy = policy
+ self._prune_versions_unlocked()
+
+ def _end_read(self, txn):
+ with self._version_lock:
+ self._readers.remove(txn)
+ self._prune_versions_unlocked()
+
+ def _end_write_unlocked(self, txn):
+ assert self._write_txn == txn
+ self._write_txn = None
+ self._maybe_wakeup_one_waiter_unlocked()
+
+ def _end_write(self, txn):
+ with self._version_lock:
+ self._end_write_unlocked(txn)
+
+ def _commit_version_unlocked(self, txn, version, origin):
+ self._versions.append(version)
+ self._prune_versions_unlocked()
+ self.nodes = version.nodes
+ if self.origin is None:
+ self.origin = origin
+ # txn can be None in __init__ when we make the empty version.
+ if txn is not None:
+ self._end_write_unlocked(txn)
+
+ def _commit_version(self, txn, version, origin):
+ with self._version_lock:
+ self._commit_version_unlocked(txn, version, origin)
+
+ def _get_next_version_id(self):
+ if len(self._versions) > 0:
+ id = self._versions[-1].id + 1
+ else:
+ id = 1
+ return id
+
+ def find_node(
+ self, name: Union[dns.name.Name, str], create: bool = False
+ ) -> dns.node.Node:
+ if create:
+ raise UseTransaction
+ return super().find_node(name)
+
+ def delete_node(self, name: Union[dns.name.Name, str]) -> None:
+ raise UseTransaction
+
+ def find_rdataset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> dns.rdataset.Rdataset:
+ if create:
+ raise UseTransaction
+ rdataset = super().find_rdataset(name, rdtype, covers)
+ return dns.rdataset.ImmutableRdataset(rdataset)
+
+ def get_rdataset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> Optional[dns.rdataset.Rdataset]:
+ if create:
+ raise UseTransaction
+ rdataset = super().get_rdataset(name, rdtype, covers)
+ if rdataset is not None:
+ return dns.rdataset.ImmutableRdataset(rdataset)
+ else:
+ return None
+
+ def delete_rdataset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ ) -> None:
+ raise UseTransaction
+
+ def replace_rdataset(
+ self, name: Union[dns.name.Name, str], replacement: dns.rdataset.Rdataset
+ ) -> None:
+ raise UseTransaction
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/win32util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/win32util.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaa7e93e328f7b25ee2271d6ebb9accf0616f78f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/win32util.py
@@ -0,0 +1,252 @@
+import sys
+
+import dns._features
+
+if sys.platform == "win32":
+ from typing import Any
+
+ import dns.name
+
+ _prefer_wmi = True
+
+ import winreg # pylint: disable=import-error
+
+ # Keep pylint quiet on non-windows.
+ try:
+ WindowsError is None # pylint: disable=used-before-assignment
+ except KeyError:
+ WindowsError = Exception
+
+ if dns._features.have("wmi"):
+ import threading
+
+ import pythoncom # pylint: disable=import-error
+ import wmi # pylint: disable=import-error
+
+ _have_wmi = True
+ else:
+ _have_wmi = False
+
+ def _config_domain(domain):
+ # Sometimes DHCP servers add a '.' prefix to the default domain, and
+ # Windows just stores such values in the registry (see #687).
+ # Check for this and fix it.
+ if domain.startswith("."):
+ domain = domain[1:]
+ return dns.name.from_text(domain)
+
+ class DnsInfo:
+ def __init__(self):
+ self.domain = None
+ self.nameservers = []
+ self.search = []
+
+ if _have_wmi:
+
+ class _WMIGetter(threading.Thread):
+ def __init__(self):
+ super().__init__()
+ self.info = DnsInfo()
+
+ def run(self):
+ pythoncom.CoInitialize()
+ try:
+ system = wmi.WMI()
+ for interface in system.Win32_NetworkAdapterConfiguration():
+ if interface.IPEnabled and interface.DNSServerSearchOrder:
+ self.info.nameservers = list(interface.DNSServerSearchOrder)
+ if interface.DNSDomain:
+ self.info.domain = _config_domain(interface.DNSDomain)
+ if interface.DNSDomainSuffixSearchOrder:
+ self.info.search = [
+ _config_domain(x)
+ for x in interface.DNSDomainSuffixSearchOrder
+ ]
+ break
+ finally:
+ pythoncom.CoUninitialize()
+
+ def get(self):
+ # We always run in a separate thread to avoid any issues with
+ # the COM threading model.
+ self.start()
+ self.join()
+ return self.info
+
+ else:
+
+ class _WMIGetter: # type: ignore
+ pass
+
+ class _RegistryGetter:
+ def __init__(self):
+ self.info = DnsInfo()
+
+ def _determine_split_char(self, entry):
+ #
+ # The windows registry irritatingly changes the list element
+ # delimiter in between ' ' and ',' (and vice-versa) in various
+ # versions of windows.
+ #
+ if entry.find(" ") >= 0:
+ split_char = " "
+ elif entry.find(",") >= 0:
+ split_char = ","
+ else:
+ # probably a singleton; treat as a space-separated list.
+ split_char = " "
+ return split_char
+
+ def _config_nameservers(self, nameservers):
+ split_char = self._determine_split_char(nameservers)
+ ns_list = nameservers.split(split_char)
+ for ns in ns_list:
+ if ns not in self.info.nameservers:
+ self.info.nameservers.append(ns)
+
+ def _config_search(self, search):
+ split_char = self._determine_split_char(search)
+ search_list = search.split(split_char)
+ for s in search_list:
+ s = _config_domain(s)
+ if s not in self.info.search:
+ self.info.search.append(s)
+
+ def _config_fromkey(self, key, always_try_domain):
+ try:
+ servers, _ = winreg.QueryValueEx(key, "NameServer")
+ except WindowsError:
+ servers = None
+ if servers:
+ self._config_nameservers(servers)
+ if servers or always_try_domain:
+ try:
+ dom, _ = winreg.QueryValueEx(key, "Domain")
+ if dom:
+ self.info.domain = _config_domain(dom)
+ except WindowsError:
+ pass
+ else:
+ try:
+ servers, _ = winreg.QueryValueEx(key, "DhcpNameServer")
+ except WindowsError:
+ servers = None
+ if servers:
+ self._config_nameservers(servers)
+ try:
+ dom, _ = winreg.QueryValueEx(key, "DhcpDomain")
+ if dom:
+ self.info.domain = _config_domain(dom)
+ except WindowsError:
+ pass
+ try:
+ search, _ = winreg.QueryValueEx(key, "SearchList")
+ except WindowsError:
+ search = None
+ if search is None:
+ try:
+ search, _ = winreg.QueryValueEx(key, "DhcpSearchList")
+ except WindowsError:
+ search = None
+ if search:
+ self._config_search(search)
+
+ def _is_nic_enabled(self, lm, guid):
+ # Look in the Windows Registry to determine whether the network
+ # interface corresponding to the given guid is enabled.
+ #
+ # (Code contributed by Paul Marks, thanks!)
+ #
+ try:
+ # This hard-coded location seems to be consistent, at least
+ # from Windows 2000 through Vista.
+ connection_key = winreg.OpenKey(
+ lm,
+ r"SYSTEM\CurrentControlSet\Control\Network"
+ r"\{4D36E972-E325-11CE-BFC1-08002BE10318}"
+ r"\%s\Connection" % guid,
+ )
+
+ try:
+ # The PnpInstanceID points to a key inside Enum
+ (pnp_id, ttype) = winreg.QueryValueEx(
+ connection_key, "PnpInstanceID"
+ )
+
+ if ttype != winreg.REG_SZ:
+ raise ValueError # pragma: no cover
+
+ device_key = winreg.OpenKey(
+ lm, r"SYSTEM\CurrentControlSet\Enum\%s" % pnp_id
+ )
+
+ try:
+ # Get ConfigFlags for this device
+ (flags, ttype) = winreg.QueryValueEx(device_key, "ConfigFlags")
+
+ if ttype != winreg.REG_DWORD:
+ raise ValueError # pragma: no cover
+
+ # Based on experimentation, bit 0x1 indicates that the
+ # device is disabled.
+ #
+ # XXXRTH I suspect we really want to & with 0x03 so
+ # that CONFIGFLAGS_REMOVED devices are also ignored,
+ # but we're shifting to WMI as ConfigFlags is not
+ # supposed to be used.
+ return not flags & 0x1
+
+ finally:
+ device_key.Close()
+ finally:
+ connection_key.Close()
+ except Exception: # pragma: no cover
+ return False
+
+ def get(self):
+ """Extract resolver configuration from the Windows registry."""
+
+ lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
+ try:
+ tcp_params = winreg.OpenKey(
+ lm, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
+ )
+ try:
+ self._config_fromkey(tcp_params, True)
+ finally:
+ tcp_params.Close()
+ interfaces = winreg.OpenKey(
+ lm,
+ r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces",
+ )
+ try:
+ i = 0
+ while True:
+ try:
+ guid = winreg.EnumKey(interfaces, i)
+ i += 1
+ key = winreg.OpenKey(interfaces, guid)
+ try:
+ if not self._is_nic_enabled(lm, guid):
+ continue
+ self._config_fromkey(key, False)
+ finally:
+ key.Close()
+ except EnvironmentError:
+ break
+ finally:
+ interfaces.Close()
+ finally:
+ lm.Close()
+ return self.info
+
+ _getter_class: Any
+ if _have_wmi and _prefer_wmi:
+ _getter_class = _WMIGetter
+ else:
+ _getter_class = _RegistryGetter
+
+ def get_dns_info():
+ """Extract resolver configuration."""
+ getter = _getter_class()
+ return getter.get()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/wire.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/wire.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f9b1573d521a924a43dde6c18a59912612798d8
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/wire.py
@@ -0,0 +1,89 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+import contextlib
+import struct
+from typing import Iterator, Optional, Tuple
+
+import dns.exception
+import dns.name
+
+
+class Parser:
+ def __init__(self, wire: bytes, current: int = 0):
+ self.wire = wire
+ self.current = 0
+ self.end = len(self.wire)
+ if current:
+ self.seek(current)
+ self.furthest = current
+
+ def remaining(self) -> int:
+ return self.end - self.current
+
+ def get_bytes(self, size: int) -> bytes:
+ assert size >= 0
+ if size > self.remaining():
+ raise dns.exception.FormError
+ output = self.wire[self.current : self.current + size]
+ self.current += size
+ self.furthest = max(self.furthest, self.current)
+ return output
+
+ def get_counted_bytes(self, length_size: int = 1) -> bytes:
+ length = int.from_bytes(self.get_bytes(length_size), "big")
+ return self.get_bytes(length)
+
+ def get_remaining(self) -> bytes:
+ return self.get_bytes(self.remaining())
+
+ def get_uint8(self) -> int:
+ return struct.unpack("!B", self.get_bytes(1))[0]
+
+ def get_uint16(self) -> int:
+ return struct.unpack("!H", self.get_bytes(2))[0]
+
+ def get_uint32(self) -> int:
+ return struct.unpack("!I", self.get_bytes(4))[0]
+
+ def get_uint48(self) -> int:
+ return int.from_bytes(self.get_bytes(6), "big")
+
+ def get_struct(self, format: str) -> Tuple:
+ return struct.unpack(format, self.get_bytes(struct.calcsize(format)))
+
+ def get_name(self, origin: Optional["dns.name.Name"] = None) -> "dns.name.Name":
+ name = dns.name.from_wire_parser(self)
+ if origin:
+ name = name.relativize(origin)
+ return name
+
+ def seek(self, where: int) -> None:
+ # Note that seeking to the end is OK! (If you try to read
+ # after such a seek, you'll get an exception as expected.)
+ if where < 0 or where > self.end:
+ raise dns.exception.FormError
+ self.current = where
+
+ @contextlib.contextmanager
+ def restrict_to(self, size: int) -> Iterator:
+ assert size >= 0
+ if size > self.remaining():
+ raise dns.exception.FormError
+ saved_end = self.end
+ try:
+ self.end = self.current + size
+ yield
+ # We make this check here and not in the finally as we
+ # don't want to raise if we're already raising for some
+ # other reason.
+ if self.current != self.end:
+ raise dns.exception.FormError
+ finally:
+ self.end = saved_end
+
+ @contextlib.contextmanager
+ def restore_furthest(self) -> Iterator:
+ try:
+ yield None
+ finally:
+ self.current = self.furthest
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/xfr.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/xfr.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd247d33db4b6e827e5c540cf0e23965b0b0e10b
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/xfr.py
@@ -0,0 +1,343 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2017 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+from typing import Any, List, Optional, Tuple, Union
+
+import dns.exception
+import dns.message
+import dns.name
+import dns.rcode
+import dns.rdataset
+import dns.rdatatype
+import dns.serial
+import dns.transaction
+import dns.tsig
+import dns.zone
+
+
+class TransferError(dns.exception.DNSException):
+ """A zone transfer response got a non-zero rcode."""
+
+ def __init__(self, rcode):
+ message = "Zone transfer error: %s" % dns.rcode.to_text(rcode)
+ super().__init__(message)
+ self.rcode = rcode
+
+
+class SerialWentBackwards(dns.exception.FormError):
+ """The current serial number is less than the serial we know."""
+
+
+class UseTCP(dns.exception.DNSException):
+ """This IXFR cannot be completed with UDP."""
+
+
+class Inbound:
+ """
+ State machine for zone transfers.
+ """
+
+ def __init__(
+ self,
+ txn_manager: dns.transaction.TransactionManager,
+ rdtype: dns.rdatatype.RdataType = dns.rdatatype.AXFR,
+ serial: Optional[int] = None,
+ is_udp: bool = False,
+ ):
+ """Initialize an inbound zone transfer.
+
+ *txn_manager* is a :py:class:`dns.transaction.TransactionManager`.
+
+ *rdtype* can be `dns.rdatatype.AXFR` or `dns.rdatatype.IXFR`
+
+ *serial* is the base serial number for IXFRs, and is required in
+ that case.
+
+ *is_udp*, a ``bool`` indidicates if UDP is being used for this
+ XFR.
+ """
+ self.txn_manager = txn_manager
+ self.txn: Optional[dns.transaction.Transaction] = None
+ self.rdtype = rdtype
+ if rdtype == dns.rdatatype.IXFR:
+ if serial is None:
+ raise ValueError("a starting serial must be supplied for IXFRs")
+ elif is_udp:
+ raise ValueError("is_udp specified for AXFR")
+ self.serial = serial
+ self.is_udp = is_udp
+ (_, _, self.origin) = txn_manager.origin_information()
+ self.soa_rdataset: Optional[dns.rdataset.Rdataset] = None
+ self.done = False
+ self.expecting_SOA = False
+ self.delete_mode = False
+
+ def process_message(self, message: dns.message.Message) -> bool:
+ """Process one message in the transfer.
+
+ The message should have the same relativization as was specified when
+ the `dns.xfr.Inbound` was created. The message should also have been
+ created with `one_rr_per_rrset=True` because order matters.
+
+ Returns `True` if the transfer is complete, and `False` otherwise.
+ """
+ if self.txn is None:
+ replacement = self.rdtype == dns.rdatatype.AXFR
+ self.txn = self.txn_manager.writer(replacement)
+ rcode = message.rcode()
+ if rcode != dns.rcode.NOERROR:
+ raise TransferError(rcode)
+ #
+ # We don't require a question section, but if it is present is
+ # should be correct.
+ #
+ if len(message.question) > 0:
+ if message.question[0].name != self.origin:
+ raise dns.exception.FormError("wrong question name")
+ if message.question[0].rdtype != self.rdtype:
+ raise dns.exception.FormError("wrong question rdatatype")
+ answer_index = 0
+ if self.soa_rdataset is None:
+ #
+ # This is the first message. We're expecting an SOA at
+ # the origin.
+ #
+ if not message.answer or message.answer[0].name != self.origin:
+ raise dns.exception.FormError("No answer or RRset not for zone origin")
+ rrset = message.answer[0]
+ rdataset = rrset
+ if rdataset.rdtype != dns.rdatatype.SOA:
+ raise dns.exception.FormError("first RRset is not an SOA")
+ answer_index = 1
+ self.soa_rdataset = rdataset.copy()
+ if self.rdtype == dns.rdatatype.IXFR:
+ if self.soa_rdataset[0].serial == self.serial:
+ #
+ # We're already up-to-date.
+ #
+ self.done = True
+ elif dns.serial.Serial(self.soa_rdataset[0].serial) < self.serial:
+ # It went backwards!
+ raise SerialWentBackwards
+ else:
+ if self.is_udp and len(message.answer[answer_index:]) == 0:
+ #
+ # There are no more records, so this is the
+ # "truncated" response. Say to use TCP
+ #
+ raise UseTCP
+ #
+ # Note we're expecting another SOA so we can detect
+ # if this IXFR response is an AXFR-style response.
+ #
+ self.expecting_SOA = True
+ #
+ # Process the answer section (other than the initial SOA in
+ # the first message).
+ #
+ for rrset in message.answer[answer_index:]:
+ name = rrset.name
+ rdataset = rrset
+ if self.done:
+ raise dns.exception.FormError("answers after final SOA")
+ assert self.txn is not None # for mypy
+ if rdataset.rdtype == dns.rdatatype.SOA and name == self.origin:
+ #
+ # Every time we see an origin SOA delete_mode inverts
+ #
+ if self.rdtype == dns.rdatatype.IXFR:
+ self.delete_mode = not self.delete_mode
+ #
+ # If this SOA Rdataset is equal to the first we saw
+ # then we're finished. If this is an IXFR we also
+ # check that we're seeing the record in the expected
+ # part of the response.
+ #
+ if rdataset == self.soa_rdataset and (
+ self.rdtype == dns.rdatatype.AXFR
+ or (self.rdtype == dns.rdatatype.IXFR and self.delete_mode)
+ ):
+ #
+ # This is the final SOA
+ #
+ if self.expecting_SOA:
+ # We got an empty IXFR sequence!
+ raise dns.exception.FormError("empty IXFR sequence")
+ if (
+ self.rdtype == dns.rdatatype.IXFR
+ and self.serial != rdataset[0].serial
+ ):
+ raise dns.exception.FormError("unexpected end of IXFR sequence")
+ self.txn.replace(name, rdataset)
+ self.txn.commit()
+ self.txn = None
+ self.done = True
+ else:
+ #
+ # This is not the final SOA
+ #
+ self.expecting_SOA = False
+ if self.rdtype == dns.rdatatype.IXFR:
+ if self.delete_mode:
+ # This is the start of an IXFR deletion set
+ if rdataset[0].serial != self.serial:
+ raise dns.exception.FormError(
+ "IXFR base serial mismatch"
+ )
+ else:
+ # This is the start of an IXFR addition set
+ self.serial = rdataset[0].serial
+ self.txn.replace(name, rdataset)
+ else:
+ # We saw a non-final SOA for the origin in an AXFR.
+ raise dns.exception.FormError("unexpected origin SOA in AXFR")
+ continue
+ if self.expecting_SOA:
+ #
+ # We made an IXFR request and are expecting another
+ # SOA RR, but saw something else, so this must be an
+ # AXFR response.
+ #
+ self.rdtype = dns.rdatatype.AXFR
+ self.expecting_SOA = False
+ self.delete_mode = False
+ self.txn.rollback()
+ self.txn = self.txn_manager.writer(True)
+ #
+ # Note we are falling through into the code below
+ # so whatever rdataset this was gets written.
+ #
+ # Add or remove the data
+ if self.delete_mode:
+ self.txn.delete_exact(name, rdataset)
+ else:
+ self.txn.add(name, rdataset)
+ if self.is_udp and not self.done:
+ #
+ # This is a UDP IXFR and we didn't get to done, and we didn't
+ # get the proper "truncated" response
+ #
+ raise dns.exception.FormError("unexpected end of UDP IXFR")
+ return self.done
+
+ #
+ # Inbounds are context managers.
+ #
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if self.txn:
+ self.txn.rollback()
+ return False
+
+
+def make_query(
+ txn_manager: dns.transaction.TransactionManager,
+ serial: Optional[int] = 0,
+ use_edns: Optional[Union[int, bool]] = None,
+ ednsflags: Optional[int] = None,
+ payload: Optional[int] = None,
+ request_payload: Optional[int] = None,
+ options: Optional[List[dns.edns.Option]] = None,
+ keyring: Any = None,
+ keyname: Optional[dns.name.Name] = None,
+ keyalgorithm: Union[dns.name.Name, str] = dns.tsig.default_algorithm,
+) -> Tuple[dns.message.QueryMessage, Optional[int]]:
+ """Make an AXFR or IXFR query.
+
+ *txn_manager* is a ``dns.transaction.TransactionManager``, typically a
+ ``dns.zone.Zone``.
+
+ *serial* is an ``int`` or ``None``. If 0, then IXFR will be
+ attempted using the most recent serial number from the
+ *txn_manager*; it is the caller's responsibility to ensure there
+ are no write transactions active that could invalidate the
+ retrieved serial. If a serial cannot be determined, AXFR will be
+ forced. Other integer values are the starting serial to use.
+ ``None`` forces an AXFR.
+
+ Please see the documentation for :py:func:`dns.message.make_query` and
+ :py:func:`dns.message.Message.use_tsig` for details on the other parameters
+ to this function.
+
+ Returns a `(query, serial)` tuple.
+ """
+ (zone_origin, _, origin) = txn_manager.origin_information()
+ if zone_origin is None:
+ raise ValueError("no zone origin")
+ if serial is None:
+ rdtype = dns.rdatatype.AXFR
+ elif not isinstance(serial, int):
+ raise ValueError("serial is not an integer")
+ elif serial == 0:
+ with txn_manager.reader() as txn:
+ rdataset = txn.get(origin, "SOA")
+ if rdataset:
+ serial = rdataset[0].serial
+ rdtype = dns.rdatatype.IXFR
+ else:
+ serial = None
+ rdtype = dns.rdatatype.AXFR
+ elif serial > 0 and serial < 4294967296:
+ rdtype = dns.rdatatype.IXFR
+ else:
+ raise ValueError("serial out-of-range")
+ rdclass = txn_manager.get_class()
+ q = dns.message.make_query(
+ zone_origin,
+ rdtype,
+ rdclass,
+ use_edns,
+ False,
+ ednsflags,
+ payload,
+ request_payload,
+ options,
+ )
+ if serial is not None:
+ rdata = dns.rdata.from_text(rdclass, "SOA", f". . {serial} 0 0 0 0")
+ rrset = q.find_rrset(
+ q.authority, zone_origin, rdclass, dns.rdatatype.SOA, create=True
+ )
+ rrset.add(rdata, 0)
+ if keyring is not None:
+ q.use_tsig(keyring, keyname, algorithm=keyalgorithm)
+ return (q, serial)
+
+
+def extract_serial_from_query(query: dns.message.Message) -> Optional[int]:
+ """Extract the SOA serial number from query if it is an IXFR and return
+ it, otherwise return None.
+
+ *query* is a dns.message.QueryMessage that is an IXFR or AXFR request.
+
+ Raises if the query is not an IXFR or AXFR, or if an IXFR doesn't have
+ an appropriate SOA RRset in the authority section.
+ """
+ if not isinstance(query, dns.message.QueryMessage):
+ raise ValueError("query not a QueryMessage")
+ question = query.question[0]
+ if question.rdtype == dns.rdatatype.AXFR:
+ return None
+ elif question.rdtype != dns.rdatatype.IXFR:
+ raise ValueError("query is not an AXFR or IXFR")
+ soa = query.find_rrset(
+ query.authority, question.name, question.rdclass, dns.rdatatype.SOA
+ )
+ return soa[0].serial
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zone.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zone.py
new file mode 100644
index 0000000000000000000000000000000000000000..844919e41f1162d44c276a329223df0e05e4dabc
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zone.py
@@ -0,0 +1,1434 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Zones."""
+
+import contextlib
+import io
+import os
+import struct
+from typing import (
+ Any,
+ Callable,
+ Iterable,
+ Iterator,
+ List,
+ MutableMapping,
+ Optional,
+ Set,
+ Tuple,
+ Union,
+)
+
+import dns.exception
+import dns.grange
+import dns.immutable
+import dns.name
+import dns.node
+import dns.rdata
+import dns.rdataclass
+import dns.rdataset
+import dns.rdatatype
+import dns.rdtypes.ANY.SOA
+import dns.rdtypes.ANY.ZONEMD
+import dns.rrset
+import dns.tokenizer
+import dns.transaction
+import dns.ttl
+import dns.zonefile
+from dns.zonetypes import DigestHashAlgorithm, DigestScheme, _digest_hashers
+
+
+class BadZone(dns.exception.DNSException):
+ """The DNS zone is malformed."""
+
+
+class NoSOA(BadZone):
+ """The DNS zone has no SOA RR at its origin."""
+
+
+class NoNS(BadZone):
+ """The DNS zone has no NS RRset at its origin."""
+
+
+class UnknownOrigin(BadZone):
+ """The DNS zone's origin is unknown."""
+
+
+class UnsupportedDigestScheme(dns.exception.DNSException):
+ """The zone digest's scheme is unsupported."""
+
+
+class UnsupportedDigestHashAlgorithm(dns.exception.DNSException):
+ """The zone digest's origin is unsupported."""
+
+
+class NoDigest(dns.exception.DNSException):
+ """The DNS zone has no ZONEMD RRset at its origin."""
+
+
+class DigestVerificationFailure(dns.exception.DNSException):
+ """The ZONEMD digest failed to verify."""
+
+
+def _validate_name(
+ name: dns.name.Name,
+ origin: Optional[dns.name.Name],
+ relativize: bool,
+) -> dns.name.Name:
+ # This name validation code is shared by Zone and Version
+ if origin is None:
+ # This should probably never happen as other code (e.g.
+ # _rr_line) will notice the lack of an origin before us, but
+ # we check just in case!
+ raise KeyError("no zone origin is defined")
+ if name.is_absolute():
+ if not name.is_subdomain(origin):
+ raise KeyError("name parameter must be a subdomain of the zone origin")
+ if relativize:
+ name = name.relativize(origin)
+ else:
+ # We have a relative name. Make sure that the derelativized name is
+ # not too long.
+ try:
+ abs_name = name.derelativize(origin)
+ except dns.name.NameTooLong:
+ # We map dns.name.NameTooLong to KeyError to be consistent with
+ # the other exceptions above.
+ raise KeyError("relative name too long for zone")
+ if not relativize:
+ # We have a relative name in a non-relative zone, so use the
+ # derelativized name.
+ name = abs_name
+ return name
+
+
+class Zone(dns.transaction.TransactionManager):
+ """A DNS zone.
+
+ A ``Zone`` is a mapping from names to nodes. The zone object may be
+ treated like a Python dictionary, e.g. ``zone[name]`` will retrieve
+ the node associated with that name. The *name* may be a
+ ``dns.name.Name object``, or it may be a string. In either case,
+ if the name is relative it is treated as relative to the origin of
+ the zone.
+ """
+
+ node_factory: Callable[[], dns.node.Node] = dns.node.Node
+ map_factory: Callable[[], MutableMapping[dns.name.Name, dns.node.Node]] = dict
+ writable_version_factory: Optional[Callable[[], "WritableVersion"]] = None
+ immutable_version_factory: Optional[Callable[[], "ImmutableVersion"]] = None
+
+ __slots__ = ["rdclass", "origin", "nodes", "relativize"]
+
+ def __init__(
+ self,
+ origin: Optional[Union[dns.name.Name, str]],
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ relativize: bool = True,
+ ):
+ """Initialize a zone object.
+
+ *origin* is the origin of the zone. It may be a ``dns.name.Name``,
+ a ``str``, or ``None``. If ``None``, then the zone's origin will
+ be set by the first ``$ORIGIN`` line in a zone file.
+
+ *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
+
+ *relativize*, a ``bool``, determine's whether domain names are
+ relativized to the zone's origin. The default is ``True``.
+ """
+
+ if origin is not None:
+ if isinstance(origin, str):
+ origin = dns.name.from_text(origin)
+ elif not isinstance(origin, dns.name.Name):
+ raise ValueError("origin parameter must be convertible to a DNS name")
+ if not origin.is_absolute():
+ raise ValueError("origin parameter must be an absolute name")
+ self.origin = origin
+ self.rdclass = rdclass
+ self.nodes: MutableMapping[dns.name.Name, dns.node.Node] = self.map_factory()
+ self.relativize = relativize
+
+ def __eq__(self, other):
+ """Two zones are equal if they have the same origin, class, and
+ nodes.
+
+ Returns a ``bool``.
+ """
+
+ if not isinstance(other, Zone):
+ return False
+ if (
+ self.rdclass != other.rdclass
+ or self.origin != other.origin
+ or self.nodes != other.nodes
+ ):
+ return False
+ return True
+
+ def __ne__(self, other):
+ """Are two zones not equal?
+
+ Returns a ``bool``.
+ """
+
+ return not self.__eq__(other)
+
+ def _validate_name(self, name: Union[dns.name.Name, str]) -> dns.name.Name:
+ # Note that any changes in this method should have corresponding changes
+ # made in the Version _validate_name() method.
+ if isinstance(name, str):
+ name = dns.name.from_text(name, None)
+ elif not isinstance(name, dns.name.Name):
+ raise KeyError("name parameter must be convertible to a DNS name")
+ return _validate_name(name, self.origin, self.relativize)
+
+ def __getitem__(self, key):
+ key = self._validate_name(key)
+ return self.nodes[key]
+
+ def __setitem__(self, key, value):
+ key = self._validate_name(key)
+ self.nodes[key] = value
+
+ def __delitem__(self, key):
+ key = self._validate_name(key)
+ del self.nodes[key]
+
+ def __iter__(self):
+ return self.nodes.__iter__()
+
+ def keys(self):
+ return self.nodes.keys()
+
+ def values(self):
+ return self.nodes.values()
+
+ def items(self):
+ return self.nodes.items()
+
+ def get(self, key):
+ key = self._validate_name(key)
+ return self.nodes.get(key)
+
+ def __contains__(self, key):
+ key = self._validate_name(key)
+ return key in self.nodes
+
+ def find_node(
+ self, name: Union[dns.name.Name, str], create: bool = False
+ ) -> dns.node.Node:
+ """Find a node in the zone, possibly creating it.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ *create*, a ``bool``. If true, the node will be created if it does
+ not exist.
+
+ Raises ``KeyError`` if the name is not known and create was
+ not specified, or if the name was not a subdomain of the origin.
+
+ Returns a ``dns.node.Node``.
+ """
+
+ name = self._validate_name(name)
+ node = self.nodes.get(name)
+ if node is None:
+ if not create:
+ raise KeyError
+ node = self.node_factory()
+ self.nodes[name] = node
+ return node
+
+ def get_node(
+ self, name: Union[dns.name.Name, str], create: bool = False
+ ) -> Optional[dns.node.Node]:
+ """Get a node in the zone, possibly creating it.
+
+ This method is like ``find_node()``, except it returns None instead
+ of raising an exception if the node does not exist and creation
+ has not been requested.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ *create*, a ``bool``. If true, the node will be created if it does
+ not exist.
+
+ Returns a ``dns.node.Node`` or ``None``.
+ """
+
+ try:
+ node = self.find_node(name, create)
+ except KeyError:
+ node = None
+ return node
+
+ def delete_node(self, name: Union[dns.name.Name, str]) -> None:
+ """Delete the specified node if it exists.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ It is not an error if the node does not exist.
+ """
+
+ name = self._validate_name(name)
+ if name in self.nodes:
+ del self.nodes[name]
+
+ def find_rdataset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> dns.rdataset.Rdataset:
+ """Look for an rdataset with the specified name and type in the zone,
+ and return an rdataset encapsulating it.
+
+ The rdataset returned is not a copy; changes to it will change
+ the zone.
+
+ KeyError is raised if the name or type are not found.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
+
+ *covers*, a ``dns.rdatatype.RdataType`` or ``str`` the covered type.
+ Usually this value is ``dns.rdatatype.NONE``, but if the
+ rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
+ then the covers value will be the rdata type the SIG/RRSIG
+ covers. The library treats the SIG and RRSIG types as if they
+ were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
+ This makes RRSIGs much easier to work with than if RRSIGs
+ covering different rdata types were aggregated into a single
+ RRSIG rdataset.
+
+ *create*, a ``bool``. If true, the node will be created if it does
+ not exist.
+
+ Raises ``KeyError`` if the name is not known and create was
+ not specified, or if the name was not a subdomain of the origin.
+
+ Returns a ``dns.rdataset.Rdataset``.
+ """
+
+ name = self._validate_name(name)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ covers = dns.rdatatype.RdataType.make(covers)
+ node = self.find_node(name, create)
+ return node.find_rdataset(self.rdclass, rdtype, covers, create)
+
+ def get_rdataset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> Optional[dns.rdataset.Rdataset]:
+ """Look for an rdataset with the specified name and type in the zone.
+
+ This method is like ``find_rdataset()``, except it returns None instead
+ of raising an exception if the rdataset does not exist and creation
+ has not been requested.
+
+ The rdataset returned is not a copy; changes to it will change
+ the zone.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
+
+ *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type.
+ Usually this value is ``dns.rdatatype.NONE``, but if the
+ rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
+ then the covers value will be the rdata type the SIG/RRSIG
+ covers. The library treats the SIG and RRSIG types as if they
+ were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
+ This makes RRSIGs much easier to work with than if RRSIGs
+ covering different rdata types were aggregated into a single
+ RRSIG rdataset.
+
+ *create*, a ``bool``. If true, the node will be created if it does
+ not exist.
+
+ Raises ``KeyError`` if the name is not known and create was
+ not specified, or if the name was not a subdomain of the origin.
+
+ Returns a ``dns.rdataset.Rdataset`` or ``None``.
+ """
+
+ try:
+ rdataset = self.find_rdataset(name, rdtype, covers, create)
+ except KeyError:
+ rdataset = None
+ return rdataset
+
+ def delete_rdataset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ ) -> None:
+ """Delete the rdataset matching *rdtype* and *covers*, if it
+ exists at the node specified by *name*.
+
+ It is not an error if the node does not exist, or if there is no matching
+ rdataset at the node.
+
+ If the node has no rdatasets after the deletion, it will itself be deleted.
+
+ *name*: the name of the node to find. The value may be a ``dns.name.Name`` or a
+ ``str``. If absolute, the name must be a subdomain of the zone's origin. If
+ ``zone.relativize`` is ``True``, then the name will be relativized.
+
+ *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
+
+ *covers*, a ``dns.rdatatype.RdataType`` or ``str`` or ``None``, the covered
+ type. Usually this value is ``dns.rdatatype.NONE``, but if the rdtype is
+ ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, then the covers value will be
+ the rdata type the SIG/RRSIG covers. The library treats the SIG and RRSIG types
+ as if they were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This
+ makes RRSIGs much easier to work with than if RRSIGs covering different rdata
+ types were aggregated into a single RRSIG rdataset.
+ """
+
+ name = self._validate_name(name)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ covers = dns.rdatatype.RdataType.make(covers)
+ node = self.get_node(name)
+ if node is not None:
+ node.delete_rdataset(self.rdclass, rdtype, covers)
+ if len(node) == 0:
+ self.delete_node(name)
+
+ def replace_rdataset(
+ self, name: Union[dns.name.Name, str], replacement: dns.rdataset.Rdataset
+ ) -> None:
+ """Replace an rdataset at name.
+
+ It is not an error if there is no rdataset matching I{replacement}.
+
+ Ownership of the *replacement* object is transferred to the zone;
+ in other words, this method does not store a copy of *replacement*
+ at the node, it stores *replacement* itself.
+
+ If the node does not exist, it is created.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ *replacement*, a ``dns.rdataset.Rdataset``, the replacement rdataset.
+ """
+
+ if replacement.rdclass != self.rdclass:
+ raise ValueError("replacement.rdclass != zone.rdclass")
+ node = self.find_node(name, True)
+ node.replace_rdataset(replacement)
+
+ def find_rrset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ ) -> dns.rrset.RRset:
+ """Look for an rdataset with the specified name and type in the zone,
+ and return an RRset encapsulating it.
+
+ This method is less efficient than the similar
+ ``find_rdataset()`` because it creates an RRset instead of
+ returning the matching rdataset. It may be more convenient
+ for some uses since it returns an object which binds the owner
+ name to the rdataset.
+
+ This method may not be used to create new nodes or rdatasets;
+ use ``find_rdataset`` instead.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
+
+ *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type.
+ Usually this value is ``dns.rdatatype.NONE``, but if the
+ rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
+ then the covers value will be the rdata type the SIG/RRSIG
+ covers. The library treats the SIG and RRSIG types as if they
+ were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
+ This makes RRSIGs much easier to work with than if RRSIGs
+ covering different rdata types were aggregated into a single
+ RRSIG rdataset.
+
+ *create*, a ``bool``. If true, the node will be created if it does
+ not exist.
+
+ Raises ``KeyError`` if the name is not known and create was
+ not specified, or if the name was not a subdomain of the origin.
+
+ Returns a ``dns.rrset.RRset`` or ``None``.
+ """
+
+ vname = self._validate_name(name)
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ covers = dns.rdatatype.RdataType.make(covers)
+ rdataset = self.nodes[vname].find_rdataset(self.rdclass, rdtype, covers)
+ rrset = dns.rrset.RRset(vname, self.rdclass, rdtype, covers)
+ rrset.update(rdataset)
+ return rrset
+
+ def get_rrset(
+ self,
+ name: Union[dns.name.Name, str],
+ rdtype: Union[dns.rdatatype.RdataType, str],
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ ) -> Optional[dns.rrset.RRset]:
+ """Look for an rdataset with the specified name and type in the zone,
+ and return an RRset encapsulating it.
+
+ This method is less efficient than the similar ``get_rdataset()``
+ because it creates an RRset instead of returning the matching
+ rdataset. It may be more convenient for some uses since it
+ returns an object which binds the owner name to the rdataset.
+
+ This method may not be used to create new nodes or rdatasets;
+ use ``get_rdataset()`` instead.
+
+ *name*: the name of the node to find.
+ The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
+ name must be a subdomain of the zone's origin. If ``zone.relativize``
+ is ``True``, then the name will be relativized.
+
+ *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired.
+
+ *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type.
+ Usually this value is ``dns.rdatatype.NONE``, but if the
+ rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
+ then the covers value will be the rdata type the SIG/RRSIG
+ covers. The library treats the SIG and RRSIG types as if they
+ were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
+ This makes RRSIGs much easier to work with than if RRSIGs
+ covering different rdata types were aggregated into a single
+ RRSIG rdataset.
+
+ *create*, a ``bool``. If true, the node will be created if it does
+ not exist.
+
+ Returns a ``dns.rrset.RRset`` or ``None``.
+ """
+
+ try:
+ rrset = self.find_rrset(name, rdtype, covers)
+ except KeyError:
+ rrset = None
+ return rrset
+
+ def iterate_rdatasets(
+ self,
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.ANY,
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]:
+ """Return a generator which yields (name, rdataset) tuples for
+ all rdatasets in the zone which have the specified *rdtype*
+ and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default,
+ then all rdatasets will be matched.
+
+ *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired.
+
+ *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type.
+ Usually this value is ``dns.rdatatype.NONE``, but if the
+ rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
+ then the covers value will be the rdata type the SIG/RRSIG
+ covers. The library treats the SIG and RRSIG types as if they
+ were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
+ This makes RRSIGs much easier to work with than if RRSIGs
+ covering different rdata types were aggregated into a single
+ RRSIG rdataset.
+ """
+
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ covers = dns.rdatatype.RdataType.make(covers)
+ for name, node in self.items():
+ for rds in node:
+ if rdtype == dns.rdatatype.ANY or (
+ rds.rdtype == rdtype and rds.covers == covers
+ ):
+ yield (name, rds)
+
+ def iterate_rdatas(
+ self,
+ rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.ANY,
+ covers: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.NONE,
+ ) -> Iterator[Tuple[dns.name.Name, int, dns.rdata.Rdata]]:
+ """Return a generator which yields (name, ttl, rdata) tuples for
+ all rdatas in the zone which have the specified *rdtype*
+ and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default,
+ then all rdatas will be matched.
+
+ *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired.
+
+ *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type.
+ Usually this value is ``dns.rdatatype.NONE``, but if the
+ rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
+ then the covers value will be the rdata type the SIG/RRSIG
+ covers. The library treats the SIG and RRSIG types as if they
+ were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
+ This makes RRSIGs much easier to work with than if RRSIGs
+ covering different rdata types were aggregated into a single
+ RRSIG rdataset.
+ """
+
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ covers = dns.rdatatype.RdataType.make(covers)
+ for name, node in self.items():
+ for rds in node:
+ if rdtype == dns.rdatatype.ANY or (
+ rds.rdtype == rdtype and rds.covers == covers
+ ):
+ for rdata in rds:
+ yield (name, rds.ttl, rdata)
+
+ def to_file(
+ self,
+ f: Any,
+ sorted: bool = True,
+ relativize: bool = True,
+ nl: Optional[str] = None,
+ want_comments: bool = False,
+ want_origin: bool = False,
+ ) -> None:
+ """Write a zone to a file.
+
+ *f*, a file or `str`. If *f* is a string, it is treated
+ as the name of a file to open.
+
+ *sorted*, a ``bool``. If True, the default, then the file
+ will be written with the names sorted in DNSSEC order from
+ least to greatest. Otherwise the names will be written in
+ whatever order they happen to have in the zone's dictionary.
+
+ *relativize*, a ``bool``. If True, the default, then domain
+ names in the output will be relativized to the zone's origin
+ if possible.
+
+ *nl*, a ``str`` or None. The end of line string. If not
+ ``None``, the output will use the platform's native
+ end-of-line marker (i.e. LF on POSIX, CRLF on Windows).
+
+ *want_comments*, a ``bool``. If ``True``, emit end-of-line comments
+ as part of writing the file. If ``False``, the default, do not
+ emit them.
+
+ *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at
+ the start of the file. If ``False``, the default, do not emit
+ one.
+ """
+
+ if isinstance(f, str):
+ cm: contextlib.AbstractContextManager = open(f, "wb")
+ else:
+ cm = contextlib.nullcontext(f)
+ with cm as f:
+ # must be in this way, f.encoding may contain None, or even
+ # attribute may not be there
+ file_enc = getattr(f, "encoding", None)
+ if file_enc is None:
+ file_enc = "utf-8"
+
+ if nl is None:
+ # binary mode, '\n' is not enough
+ nl_b = os.linesep.encode(file_enc)
+ nl = "\n"
+ elif isinstance(nl, str):
+ nl_b = nl.encode(file_enc)
+ else:
+ nl_b = nl
+ nl = nl.decode()
+
+ if want_origin:
+ assert self.origin is not None
+ l = "$ORIGIN " + self.origin.to_text()
+ l_b = l.encode(file_enc)
+ try:
+ f.write(l_b)
+ f.write(nl_b)
+ except TypeError: # textual mode
+ f.write(l)
+ f.write(nl)
+
+ if sorted:
+ names = list(self.keys())
+ names.sort()
+ else:
+ names = self.keys()
+ for n in names:
+ l = self[n].to_text(
+ n,
+ origin=self.origin,
+ relativize=relativize,
+ want_comments=want_comments,
+ )
+ l_b = l.encode(file_enc)
+
+ try:
+ f.write(l_b)
+ f.write(nl_b)
+ except TypeError: # textual mode
+ f.write(l)
+ f.write(nl)
+
+ def to_text(
+ self,
+ sorted: bool = True,
+ relativize: bool = True,
+ nl: Optional[str] = None,
+ want_comments: bool = False,
+ want_origin: bool = False,
+ ) -> str:
+ """Return a zone's text as though it were written to a file.
+
+ *sorted*, a ``bool``. If True, the default, then the file
+ will be written with the names sorted in DNSSEC order from
+ least to greatest. Otherwise the names will be written in
+ whatever order they happen to have in the zone's dictionary.
+
+ *relativize*, a ``bool``. If True, the default, then domain
+ names in the output will be relativized to the zone's origin
+ if possible.
+
+ *nl*, a ``str`` or None. The end of line string. If not
+ ``None``, the output will use the platform's native
+ end-of-line marker (i.e. LF on POSIX, CRLF on Windows).
+
+ *want_comments*, a ``bool``. If ``True``, emit end-of-line comments
+ as part of writing the file. If ``False``, the default, do not
+ emit them.
+
+ *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at
+ the start of the output. If ``False``, the default, do not emit
+ one.
+
+ Returns a ``str``.
+ """
+ temp_buffer = io.StringIO()
+ self.to_file(temp_buffer, sorted, relativize, nl, want_comments, want_origin)
+ return_value = temp_buffer.getvalue()
+ temp_buffer.close()
+ return return_value
+
+ def check_origin(self) -> None:
+ """Do some simple checking of the zone's origin.
+
+ Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
+
+ Raises ``dns.zone.NoNS`` if there is no NS RRset.
+
+ Raises ``KeyError`` if there is no origin node.
+ """
+ if self.relativize:
+ name = dns.name.empty
+ else:
+ assert self.origin is not None
+ name = self.origin
+ if self.get_rdataset(name, dns.rdatatype.SOA) is None:
+ raise NoSOA
+ if self.get_rdataset(name, dns.rdatatype.NS) is None:
+ raise NoNS
+
+ def get_soa(
+ self, txn: Optional[dns.transaction.Transaction] = None
+ ) -> dns.rdtypes.ANY.SOA.SOA:
+ """Get the zone SOA rdata.
+
+ Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
+
+ Returns a ``dns.rdtypes.ANY.SOA.SOA`` Rdata.
+ """
+ if self.relativize:
+ origin_name = dns.name.empty
+ else:
+ if self.origin is None:
+ # get_soa() has been called very early, and there must not be
+ # an SOA if there is no origin.
+ raise NoSOA
+ origin_name = self.origin
+ soa: Optional[dns.rdataset.Rdataset]
+ if txn:
+ soa = txn.get(origin_name, dns.rdatatype.SOA)
+ else:
+ soa = self.get_rdataset(origin_name, dns.rdatatype.SOA)
+ if soa is None:
+ raise NoSOA
+ return soa[0]
+
+ def _compute_digest(
+ self,
+ hash_algorithm: DigestHashAlgorithm,
+ scheme: DigestScheme = DigestScheme.SIMPLE,
+ ) -> bytes:
+ hashinfo = _digest_hashers.get(hash_algorithm)
+ if not hashinfo:
+ raise UnsupportedDigestHashAlgorithm
+ if scheme != DigestScheme.SIMPLE:
+ raise UnsupportedDigestScheme
+
+ if self.relativize:
+ origin_name = dns.name.empty
+ else:
+ assert self.origin is not None
+ origin_name = self.origin
+ hasher = hashinfo()
+ for name, node in sorted(self.items()):
+ rrnamebuf = name.to_digestable(self.origin)
+ for rdataset in sorted(node, key=lambda rds: (rds.rdtype, rds.covers)):
+ if name == origin_name and dns.rdatatype.ZONEMD in (
+ rdataset.rdtype,
+ rdataset.covers,
+ ):
+ continue
+ rrfixed = struct.pack(
+ "!HHI", rdataset.rdtype, rdataset.rdclass, rdataset.ttl
+ )
+ rdatas = [rdata.to_digestable(self.origin) for rdata in rdataset]
+ for rdata in sorted(rdatas):
+ rrlen = struct.pack("!H", len(rdata))
+ hasher.update(rrnamebuf + rrfixed + rrlen + rdata)
+ return hasher.digest()
+
+ def compute_digest(
+ self,
+ hash_algorithm: DigestHashAlgorithm,
+ scheme: DigestScheme = DigestScheme.SIMPLE,
+ ) -> dns.rdtypes.ANY.ZONEMD.ZONEMD:
+ serial = self.get_soa().serial
+ digest = self._compute_digest(hash_algorithm, scheme)
+ return dns.rdtypes.ANY.ZONEMD.ZONEMD(
+ self.rdclass, dns.rdatatype.ZONEMD, serial, scheme, hash_algorithm, digest
+ )
+
+ def verify_digest(
+ self, zonemd: Optional[dns.rdtypes.ANY.ZONEMD.ZONEMD] = None
+ ) -> None:
+ digests: Union[dns.rdataset.Rdataset, List[dns.rdtypes.ANY.ZONEMD.ZONEMD]]
+ if zonemd:
+ digests = [zonemd]
+ else:
+ assert self.origin is not None
+ rds = self.get_rdataset(self.origin, dns.rdatatype.ZONEMD)
+ if rds is None:
+ raise NoDigest
+ digests = rds
+ for digest in digests:
+ try:
+ computed = self._compute_digest(digest.hash_algorithm, digest.scheme)
+ if computed == digest.digest:
+ return
+ except Exception:
+ pass
+ raise DigestVerificationFailure
+
+ # TransactionManager methods
+
+ def reader(self) -> "Transaction":
+ return Transaction(self, False, Version(self, 1, self.nodes, self.origin))
+
+ def writer(self, replacement: bool = False) -> "Transaction":
+ txn = Transaction(self, replacement)
+ txn._setup_version()
+ return txn
+
+ def origin_information(
+ self,
+ ) -> Tuple[Optional[dns.name.Name], bool, Optional[dns.name.Name]]:
+ effective: Optional[dns.name.Name]
+ if self.relativize:
+ effective = dns.name.empty
+ else:
+ effective = self.origin
+ return (self.origin, self.relativize, effective)
+
+ def get_class(self):
+ return self.rdclass
+
+ # Transaction methods
+
+ def _end_read(self, txn):
+ pass
+
+ def _end_write(self, txn):
+ pass
+
+ def _commit_version(self, _, version, origin):
+ self.nodes = version.nodes
+ if self.origin is None:
+ self.origin = origin
+
+ def _get_next_version_id(self):
+ # Versions are ephemeral and all have id 1
+ return 1
+
+
+# These classes used to be in dns.versioned, but have moved here so we can use
+# the copy-on-write transaction mechanism for both kinds of zones. In a
+# regular zone, the version only exists during the transaction, and the nodes
+# are regular dns.node.Nodes.
+
+# A node with a version id.
+
+
+class VersionedNode(dns.node.Node): # lgtm[py/missing-equals]
+ __slots__ = ["id"]
+
+ def __init__(self):
+ super().__init__()
+ # A proper id will get set by the Version
+ self.id = 0
+
+
+@dns.immutable.immutable
+class ImmutableVersionedNode(VersionedNode):
+ def __init__(self, node):
+ super().__init__()
+ self.id = node.id
+ self.rdatasets = tuple(
+ [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets]
+ )
+
+ def find_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> dns.rdataset.Rdataset:
+ if create:
+ raise TypeError("immutable")
+ return super().find_rdataset(rdclass, rdtype, covers, False)
+
+ def get_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ create: bool = False,
+ ) -> Optional[dns.rdataset.Rdataset]:
+ if create:
+ raise TypeError("immutable")
+ return super().get_rdataset(rdclass, rdtype, covers, False)
+
+ def delete_rdataset(
+ self,
+ rdclass: dns.rdataclass.RdataClass,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
+ ) -> None:
+ raise TypeError("immutable")
+
+ def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None:
+ raise TypeError("immutable")
+
+ def is_immutable(self) -> bool:
+ return True
+
+
+class Version:
+ def __init__(
+ self,
+ zone: Zone,
+ id: int,
+ nodes: Optional[MutableMapping[dns.name.Name, dns.node.Node]] = None,
+ origin: Optional[dns.name.Name] = None,
+ ):
+ self.zone = zone
+ self.id = id
+ if nodes is not None:
+ self.nodes = nodes
+ else:
+ self.nodes = zone.map_factory()
+ self.origin = origin
+
+ def _validate_name(self, name: dns.name.Name) -> dns.name.Name:
+ return _validate_name(name, self.origin, self.zone.relativize)
+
+ def get_node(self, name: dns.name.Name) -> Optional[dns.node.Node]:
+ name = self._validate_name(name)
+ return self.nodes.get(name)
+
+ def get_rdataset(
+ self,
+ name: dns.name.Name,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType,
+ ) -> Optional[dns.rdataset.Rdataset]:
+ node = self.get_node(name)
+ if node is None:
+ return None
+ return node.get_rdataset(self.zone.rdclass, rdtype, covers)
+
+ def keys(self):
+ return self.nodes.keys()
+
+ def items(self):
+ return self.nodes.items()
+
+
+class WritableVersion(Version):
+ def __init__(self, zone: Zone, replacement: bool = False):
+ # The zone._versions_lock must be held by our caller in a versioned
+ # zone.
+ id = zone._get_next_version_id()
+ super().__init__(zone, id)
+ if not replacement:
+ # We copy the map, because that gives us a simple and thread-safe
+ # way of doing versions, and we have a garbage collector to help
+ # us. We only make new node objects if we actually change the
+ # node.
+ self.nodes.update(zone.nodes)
+ # We have to copy the zone origin as it may be None in the first
+ # version, and we don't want to mutate the zone until we commit.
+ self.origin = zone.origin
+ self.changed: Set[dns.name.Name] = set()
+
+ def _maybe_cow(self, name: dns.name.Name) -> dns.node.Node:
+ name = self._validate_name(name)
+ node = self.nodes.get(name)
+ if node is None or name not in self.changed:
+ new_node = self.zone.node_factory()
+ if hasattr(new_node, "id"):
+ # We keep doing this for backwards compatibility, as earlier
+ # code used new_node.id != self.id for the "do we need to CoW?"
+ # test. Now we use the changed set as this works with both
+ # regular zones and versioned zones.
+ #
+ # We ignore the mypy error as this is safe but it doesn't see it.
+ new_node.id = self.id # type: ignore
+ if node is not None:
+ # moo! copy on write!
+ new_node.rdatasets.extend(node.rdatasets)
+ self.nodes[name] = new_node
+ self.changed.add(name)
+ return new_node
+ else:
+ return node
+
+ def delete_node(self, name: dns.name.Name) -> None:
+ name = self._validate_name(name)
+ if name in self.nodes:
+ del self.nodes[name]
+ self.changed.add(name)
+
+ def put_rdataset(
+ self, name: dns.name.Name, rdataset: dns.rdataset.Rdataset
+ ) -> None:
+ node = self._maybe_cow(name)
+ node.replace_rdataset(rdataset)
+
+ def delete_rdataset(
+ self,
+ name: dns.name.Name,
+ rdtype: dns.rdatatype.RdataType,
+ covers: dns.rdatatype.RdataType,
+ ) -> None:
+ node = self._maybe_cow(name)
+ node.delete_rdataset(self.zone.rdclass, rdtype, covers)
+ if len(node) == 0:
+ del self.nodes[name]
+
+
+@dns.immutable.immutable
+class ImmutableVersion(Version):
+ def __init__(self, version: WritableVersion):
+ # We tell super() that it's a replacement as we don't want it
+ # to copy the nodes, as we're about to do that with an
+ # immutable Dict.
+ super().__init__(version.zone, True)
+ # set the right id!
+ self.id = version.id
+ # keep the origin
+ self.origin = version.origin
+ # Make changed nodes immutable
+ for name in version.changed:
+ node = version.nodes.get(name)
+ # it might not exist if we deleted it in the version
+ if node:
+ version.nodes[name] = ImmutableVersionedNode(node)
+ # We're changing the type of the nodes dictionary here on purpose, so
+ # we ignore the mypy error.
+ self.nodes = dns.immutable.Dict(
+ version.nodes, True, self.zone.map_factory
+ ) # type: ignore
+
+
+class Transaction(dns.transaction.Transaction):
+ def __init__(self, zone, replacement, version=None, make_immutable=False):
+ read_only = version is not None
+ super().__init__(zone, replacement, read_only)
+ self.version = version
+ self.make_immutable = make_immutable
+
+ @property
+ def zone(self):
+ return self.manager
+
+ def _setup_version(self):
+ assert self.version is None
+ factory = self.manager.writable_version_factory
+ if factory is None:
+ factory = WritableVersion
+ self.version = factory(self.zone, self.replacement)
+
+ def _get_rdataset(self, name, rdtype, covers):
+ return self.version.get_rdataset(name, rdtype, covers)
+
+ def _put_rdataset(self, name, rdataset):
+ assert not self.read_only
+ self.version.put_rdataset(name, rdataset)
+
+ def _delete_name(self, name):
+ assert not self.read_only
+ self.version.delete_node(name)
+
+ def _delete_rdataset(self, name, rdtype, covers):
+ assert not self.read_only
+ self.version.delete_rdataset(name, rdtype, covers)
+
+ def _name_exists(self, name):
+ return self.version.get_node(name) is not None
+
+ def _changed(self):
+ if self.read_only:
+ return False
+ else:
+ return len(self.version.changed) > 0
+
+ def _end_transaction(self, commit):
+ if self.read_only:
+ self.zone._end_read(self)
+ elif commit and len(self.version.changed) > 0:
+ if self.make_immutable:
+ factory = self.manager.immutable_version_factory
+ if factory is None:
+ factory = ImmutableVersion
+ version = factory(self.version)
+ else:
+ version = self.version
+ self.zone._commit_version(self, version, self.version.origin)
+ else:
+ # rollback
+ self.zone._end_write(self)
+
+ def _set_origin(self, origin):
+ if self.version.origin is None:
+ self.version.origin = origin
+
+ def _iterate_rdatasets(self):
+ for name, node in self.version.items():
+ for rdataset in node:
+ yield (name, rdataset)
+
+ def _iterate_names(self):
+ return self.version.keys()
+
+ def _get_node(self, name):
+ return self.version.get_node(name)
+
+ def _origin_information(self):
+ (absolute, relativize, effective) = self.manager.origin_information()
+ if absolute is None and self.version.origin is not None:
+ # No origin has been committed yet, but we've learned one as part of
+ # this txn. Use it.
+ absolute = self.version.origin
+ if relativize:
+ effective = dns.name.empty
+ else:
+ effective = absolute
+ return (absolute, relativize, effective)
+
+
+def _from_text(
+ text: Any,
+ origin: Optional[Union[dns.name.Name, str]] = None,
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ relativize: bool = True,
+ zone_factory: Any = Zone,
+ filename: Optional[str] = None,
+ allow_include: bool = False,
+ check_origin: bool = True,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ allow_directives: Union[bool, Iterable[str]] = True,
+) -> Zone:
+ # See the comments for the public APIs from_text() and from_file() for
+ # details.
+
+ # 'text' can also be a file, but we don't publish that fact
+ # since it's an implementation detail. The official file
+ # interface is from_file().
+
+ if filename is None:
+ filename = ""
+ zone = zone_factory(origin, rdclass, relativize=relativize)
+ with zone.writer(True) as txn:
+ tok = dns.tokenizer.Tokenizer(text, filename, idna_codec=idna_codec)
+ reader = dns.zonefile.Reader(
+ tok,
+ rdclass,
+ txn,
+ allow_include=allow_include,
+ allow_directives=allow_directives,
+ )
+ try:
+ reader.read()
+ except dns.zonefile.UnknownOrigin:
+ # for backwards compatibility
+ raise dns.zone.UnknownOrigin
+ # Now that we're done reading, do some basic checking of the zone.
+ if check_origin:
+ zone.check_origin()
+ return zone
+
+
+def from_text(
+ text: str,
+ origin: Optional[Union[dns.name.Name, str]] = None,
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ relativize: bool = True,
+ zone_factory: Any = Zone,
+ filename: Optional[str] = None,
+ allow_include: bool = False,
+ check_origin: bool = True,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ allow_directives: Union[bool, Iterable[str]] = True,
+) -> Zone:
+ """Build a zone object from a zone file format string.
+
+ *text*, a ``str``, the zone file format input.
+
+ *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin
+ of the zone; if not specified, the first ``$ORIGIN`` statement in the
+ zone file will determine the origin of the zone.
+
+ *rdclass*, a ``dns.rdataclass.RdataClass``, the zone's rdata class; the default is
+ class IN.
+
+ *relativize*, a ``bool``, determine's whether domain names are
+ relativized to the zone's origin. The default is ``True``.
+
+ *zone_factory*, the zone factory to use or ``None``. If ``None``, then
+ ``dns.zone.Zone`` will be used. The value may be any class or callable
+ that returns a subclass of ``dns.zone.Zone``.
+
+ *filename*, a ``str`` or ``None``, the filename to emit when
+ describing where an error occurred; the default is ``''``.
+
+ *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE``
+ directives are permitted. If ``False``, then encoutering a ``$INCLUDE``
+ will raise a ``SyntaxError`` exception.
+
+ *check_origin*, a ``bool``. If ``True``, the default, then sanity
+ checks of the origin node will be made by calling the zone's
+ ``check_origin()`` method.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default,
+ then directives are permitted, and the *allow_include* parameter controls whether
+ ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive
+ processing is done and any directive-like text will be treated as a regular owner
+ name. If a non-empty iterable, then only the listed directives (including the
+ ``$``) are allowed.
+
+ Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
+
+ Raises ``dns.zone.NoNS`` if there is no NS RRset.
+
+ Raises ``KeyError`` if there is no origin node.
+
+ Returns a subclass of ``dns.zone.Zone``.
+ """
+ return _from_text(
+ text,
+ origin,
+ rdclass,
+ relativize,
+ zone_factory,
+ filename,
+ allow_include,
+ check_origin,
+ idna_codec,
+ allow_directives,
+ )
+
+
+def from_file(
+ f: Any,
+ origin: Optional[Union[dns.name.Name, str]] = None,
+ rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
+ relativize: bool = True,
+ zone_factory: Any = Zone,
+ filename: Optional[str] = None,
+ allow_include: bool = True,
+ check_origin: bool = True,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ allow_directives: Union[bool, Iterable[str]] = True,
+) -> Zone:
+ """Read a zone file and build a zone object.
+
+ *f*, a file or ``str``. If *f* is a string, it is treated
+ as the name of a file to open.
+
+ *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin
+ of the zone; if not specified, the first ``$ORIGIN`` statement in the
+ zone file will determine the origin of the zone.
+
+ *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
+
+ *relativize*, a ``bool``, determine's whether domain names are
+ relativized to the zone's origin. The default is ``True``.
+
+ *zone_factory*, the zone factory to use or ``None``. If ``None``, then
+ ``dns.zone.Zone`` will be used. The value may be any class or callable
+ that returns a subclass of ``dns.zone.Zone``.
+
+ *filename*, a ``str`` or ``None``, the filename to emit when
+ describing where an error occurred; the default is ``''``.
+
+ *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE``
+ directives are permitted. If ``False``, then encoutering a ``$INCLUDE``
+ will raise a ``SyntaxError`` exception.
+
+ *check_origin*, a ``bool``. If ``True``, the default, then sanity
+ checks of the origin node will be made by calling the zone's
+ ``check_origin()`` method.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used.
+
+ *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default,
+ then directives are permitted, and the *allow_include* parameter controls whether
+ ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive
+ processing is done and any directive-like text will be treated as a regular owner
+ name. If a non-empty iterable, then only the listed directives (including the
+ ``$``) are allowed.
+
+ Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
+
+ Raises ``dns.zone.NoNS`` if there is no NS RRset.
+
+ Raises ``KeyError`` if there is no origin node.
+
+ Returns a subclass of ``dns.zone.Zone``.
+ """
+
+ if isinstance(f, str):
+ if filename is None:
+ filename = f
+ cm: contextlib.AbstractContextManager = open(f)
+ else:
+ cm = contextlib.nullcontext(f)
+ with cm as f:
+ return _from_text(
+ f,
+ origin,
+ rdclass,
+ relativize,
+ zone_factory,
+ filename,
+ allow_include,
+ check_origin,
+ idna_codec,
+ allow_directives,
+ )
+ assert False # make mypy happy lgtm[py/unreachable-statement]
+
+
+def from_xfr(
+ xfr: Any,
+ zone_factory: Any = Zone,
+ relativize: bool = True,
+ check_origin: bool = True,
+) -> Zone:
+ """Convert the output of a zone transfer generator into a zone object.
+
+ *xfr*, a generator of ``dns.message.Message`` objects, typically
+ ``dns.query.xfr()``.
+
+ *relativize*, a ``bool``, determine's whether domain names are
+ relativized to the zone's origin. The default is ``True``.
+ It is essential that the relativize setting matches the one specified
+ to the generator.
+
+ *check_origin*, a ``bool``. If ``True``, the default, then sanity
+ checks of the origin node will be made by calling the zone's
+ ``check_origin()`` method.
+
+ Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
+
+ Raises ``dns.zone.NoNS`` if there is no NS RRset.
+
+ Raises ``KeyError`` if there is no origin node.
+
+ Raises ``ValueError`` if no messages are yielded by the generator.
+
+ Returns a subclass of ``dns.zone.Zone``.
+ """
+
+ z = None
+ for r in xfr:
+ if z is None:
+ if relativize:
+ origin = r.origin
+ else:
+ origin = r.answer[0].name
+ rdclass = r.answer[0].rdclass
+ z = zone_factory(origin, rdclass, relativize=relativize)
+ for rrset in r.answer:
+ znode = z.nodes.get(rrset.name)
+ if not znode:
+ znode = z.node_factory()
+ z.nodes[rrset.name] = znode
+ zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype, rrset.covers, True)
+ zrds.update_ttl(rrset.ttl)
+ for rd in rrset:
+ zrds.add(rd)
+ if z is None:
+ raise ValueError("empty transfer")
+ if check_origin:
+ z.check_origin()
+ return z
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zonefile.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zonefile.py
new file mode 100644
index 0000000000000000000000000000000000000000..af064e730eb327403209281934bd0f63da09cae4
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zonefile.py
@@ -0,0 +1,746 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose with or without fee is hereby granted,
+# provided that the above copyright notice and this permission notice
+# appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""DNS Zones."""
+
+import re
+import sys
+from typing import Any, Iterable, List, Optional, Set, Tuple, Union
+
+import dns.exception
+import dns.grange
+import dns.name
+import dns.node
+import dns.rdata
+import dns.rdataclass
+import dns.rdatatype
+import dns.rdtypes.ANY.SOA
+import dns.rrset
+import dns.tokenizer
+import dns.transaction
+import dns.ttl
+
+
+class UnknownOrigin(dns.exception.DNSException):
+ """Unknown origin"""
+
+
+class CNAMEAndOtherData(dns.exception.DNSException):
+ """A node has a CNAME and other data"""
+
+
+def _check_cname_and_other_data(txn, name, rdataset):
+ rdataset_kind = dns.node.NodeKind.classify_rdataset(rdataset)
+ node = txn.get_node(name)
+ if node is None:
+ # empty nodes are neutral.
+ return
+ node_kind = node.classify()
+ if (
+ node_kind == dns.node.NodeKind.CNAME
+ and rdataset_kind == dns.node.NodeKind.REGULAR
+ ):
+ raise CNAMEAndOtherData("rdataset type is not compatible with a CNAME node")
+ elif (
+ node_kind == dns.node.NodeKind.REGULAR
+ and rdataset_kind == dns.node.NodeKind.CNAME
+ ):
+ raise CNAMEAndOtherData(
+ "CNAME rdataset is not compatible with a regular data node"
+ )
+ # Otherwise at least one of the node and the rdataset is neutral, so
+ # adding the rdataset is ok
+
+
+SavedStateType = Tuple[
+ dns.tokenizer.Tokenizer,
+ Optional[dns.name.Name], # current_origin
+ Optional[dns.name.Name], # last_name
+ Optional[Any], # current_file
+ int, # last_ttl
+ bool, # last_ttl_known
+ int, # default_ttl
+ bool,
+] # default_ttl_known
+
+
+def _upper_dollarize(s):
+ s = s.upper()
+ if not s.startswith("$"):
+ s = "$" + s
+ return s
+
+
+class Reader:
+ """Read a DNS zone file into a transaction."""
+
+ def __init__(
+ self,
+ tok: dns.tokenizer.Tokenizer,
+ rdclass: dns.rdataclass.RdataClass,
+ txn: dns.transaction.Transaction,
+ allow_include: bool = False,
+ allow_directives: Union[bool, Iterable[str]] = True,
+ force_name: Optional[dns.name.Name] = None,
+ force_ttl: Optional[int] = None,
+ force_rdclass: Optional[dns.rdataclass.RdataClass] = None,
+ force_rdtype: Optional[dns.rdatatype.RdataType] = None,
+ default_ttl: Optional[int] = None,
+ ):
+ self.tok = tok
+ (self.zone_origin, self.relativize, _) = txn.manager.origin_information()
+ self.current_origin = self.zone_origin
+ self.last_ttl = 0
+ self.last_ttl_known = False
+ if force_ttl is not None:
+ default_ttl = force_ttl
+ if default_ttl is None:
+ self.default_ttl = 0
+ self.default_ttl_known = False
+ else:
+ self.default_ttl = default_ttl
+ self.default_ttl_known = True
+ self.last_name = self.current_origin
+ self.zone_rdclass = rdclass
+ self.txn = txn
+ self.saved_state: List[SavedStateType] = []
+ self.current_file: Optional[Any] = None
+ self.allowed_directives: Set[str]
+ if allow_directives is True:
+ self.allowed_directives = {"$GENERATE", "$ORIGIN", "$TTL"}
+ if allow_include:
+ self.allowed_directives.add("$INCLUDE")
+ elif allow_directives is False:
+ # allow_include was ignored in earlier releases if allow_directives was
+ # False, so we continue that.
+ self.allowed_directives = set()
+ else:
+ # Note that if directives are explicitly specified, then allow_include
+ # is ignored.
+ self.allowed_directives = set(_upper_dollarize(d) for d in allow_directives)
+ self.force_name = force_name
+ self.force_ttl = force_ttl
+ self.force_rdclass = force_rdclass
+ self.force_rdtype = force_rdtype
+ self.txn.check_put_rdataset(_check_cname_and_other_data)
+
+ def _eat_line(self):
+ while 1:
+ token = self.tok.get()
+ if token.is_eol_or_eof():
+ break
+
+ def _get_identifier(self):
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ return token
+
+ def _rr_line(self):
+ """Process one line from a DNS zone file."""
+ token = None
+ # Name
+ if self.force_name is not None:
+ name = self.force_name
+ else:
+ if self.current_origin is None:
+ raise UnknownOrigin
+ token = self.tok.get(want_leading=True)
+ if not token.is_whitespace():
+ self.last_name = self.tok.as_name(token, self.current_origin)
+ else:
+ token = self.tok.get()
+ if token.is_eol_or_eof():
+ # treat leading WS followed by EOL/EOF as if they were EOL/EOF.
+ return
+ self.tok.unget(token)
+ name = self.last_name
+ if not name.is_subdomain(self.zone_origin):
+ self._eat_line()
+ return
+ if self.relativize:
+ name = name.relativize(self.zone_origin)
+
+ # TTL
+ if self.force_ttl is not None:
+ ttl = self.force_ttl
+ self.last_ttl = ttl
+ self.last_ttl_known = True
+ else:
+ token = self._get_identifier()
+ ttl = None
+ try:
+ ttl = dns.ttl.from_text(token.value)
+ self.last_ttl = ttl
+ self.last_ttl_known = True
+ token = None
+ except dns.ttl.BadTTL:
+ self.tok.unget(token)
+
+ # Class
+ if self.force_rdclass is not None:
+ rdclass = self.force_rdclass
+ else:
+ token = self._get_identifier()
+ try:
+ rdclass = dns.rdataclass.from_text(token.value)
+ except dns.exception.SyntaxError:
+ raise
+ except Exception:
+ rdclass = self.zone_rdclass
+ self.tok.unget(token)
+ if rdclass != self.zone_rdclass:
+ raise dns.exception.SyntaxError("RR class is not zone's class")
+
+ if ttl is None:
+ # support for syntax
+ token = self._get_identifier()
+ ttl = None
+ try:
+ ttl = dns.ttl.from_text(token.value)
+ self.last_ttl = ttl
+ self.last_ttl_known = True
+ token = None
+ except dns.ttl.BadTTL:
+ if self.default_ttl_known:
+ ttl = self.default_ttl
+ elif self.last_ttl_known:
+ ttl = self.last_ttl
+ self.tok.unget(token)
+
+ # Type
+ if self.force_rdtype is not None:
+ rdtype = self.force_rdtype
+ else:
+ token = self._get_identifier()
+ try:
+ rdtype = dns.rdatatype.from_text(token.value)
+ except Exception:
+ raise dns.exception.SyntaxError("unknown rdatatype '%s'" % token.value)
+
+ try:
+ rd = dns.rdata.from_text(
+ rdclass,
+ rdtype,
+ self.tok,
+ self.current_origin,
+ self.relativize,
+ self.zone_origin,
+ )
+ except dns.exception.SyntaxError:
+ # Catch and reraise.
+ raise
+ except Exception:
+ # All exceptions that occur in the processing of rdata
+ # are treated as syntax errors. This is not strictly
+ # correct, but it is correct almost all of the time.
+ # We convert them to syntax errors so that we can emit
+ # helpful filename:line info.
+ (ty, va) = sys.exc_info()[:2]
+ raise dns.exception.SyntaxError(
+ "caught exception {}: {}".format(str(ty), str(va))
+ )
+
+ if not self.default_ttl_known and rdtype == dns.rdatatype.SOA:
+ # The pre-RFC2308 and pre-BIND9 behavior inherits the zone default
+ # TTL from the SOA minttl if no $TTL statement is present before the
+ # SOA is parsed.
+ self.default_ttl = rd.minimum
+ self.default_ttl_known = True
+ if ttl is None:
+ # if we didn't have a TTL on the SOA, set it!
+ ttl = rd.minimum
+
+ # TTL check. We had to wait until now to do this as the SOA RR's
+ # own TTL can be inferred from its minimum.
+ if ttl is None:
+ raise dns.exception.SyntaxError("Missing default TTL value")
+
+ self.txn.add(name, ttl, rd)
+
+ def _parse_modify(self, side: str) -> Tuple[str, str, int, int, str]:
+ # Here we catch everything in '{' '}' in a group so we can replace it
+ # with ''.
+ is_generate1 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+),(.)}).*$")
+ is_generate2 = re.compile(r"^.*\$({(\+|-?)(\d+)}).*$")
+ is_generate3 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+)}).*$")
+ # Sometimes there are modifiers in the hostname. These come after
+ # the dollar sign. They are in the form: ${offset[,width[,base]]}.
+ # Make names
+ g1 = is_generate1.match(side)
+ if g1:
+ mod, sign, offset, width, base = g1.groups()
+ if sign == "":
+ sign = "+"
+ g2 = is_generate2.match(side)
+ if g2:
+ mod, sign, offset = g2.groups()
+ if sign == "":
+ sign = "+"
+ width = 0
+ base = "d"
+ g3 = is_generate3.match(side)
+ if g3:
+ mod, sign, offset, width = g3.groups()
+ if sign == "":
+ sign = "+"
+ base = "d"
+
+ if not (g1 or g2 or g3):
+ mod = ""
+ sign = "+"
+ offset = 0
+ width = 0
+ base = "d"
+
+ offset = int(offset)
+ width = int(width)
+
+ if sign not in ["+", "-"]:
+ raise dns.exception.SyntaxError("invalid offset sign %s" % sign)
+ if base not in ["d", "o", "x", "X", "n", "N"]:
+ raise dns.exception.SyntaxError("invalid type %s" % base)
+
+ return mod, sign, offset, width, base
+
+ def _generate_line(self):
+ # range lhs [ttl] [class] type rhs [ comment ]
+ """Process one line containing the GENERATE statement from a DNS
+ zone file."""
+ if self.current_origin is None:
+ raise UnknownOrigin
+
+ token = self.tok.get()
+ # Range (required)
+ try:
+ start, stop, step = dns.grange.from_text(token.value)
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except Exception:
+ raise dns.exception.SyntaxError
+
+ # lhs (required)
+ try:
+ lhs = token.value
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except Exception:
+ raise dns.exception.SyntaxError
+
+ # TTL
+ try:
+ ttl = dns.ttl.from_text(token.value)
+ self.last_ttl = ttl
+ self.last_ttl_known = True
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except dns.ttl.BadTTL:
+ if not (self.last_ttl_known or self.default_ttl_known):
+ raise dns.exception.SyntaxError("Missing default TTL value")
+ if self.default_ttl_known:
+ ttl = self.default_ttl
+ elif self.last_ttl_known:
+ ttl = self.last_ttl
+ # Class
+ try:
+ rdclass = dns.rdataclass.from_text(token.value)
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except dns.exception.SyntaxError:
+ raise dns.exception.SyntaxError
+ except Exception:
+ rdclass = self.zone_rdclass
+ if rdclass != self.zone_rdclass:
+ raise dns.exception.SyntaxError("RR class is not zone's class")
+ # Type
+ try:
+ rdtype = dns.rdatatype.from_text(token.value)
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError
+ except Exception:
+ raise dns.exception.SyntaxError("unknown rdatatype '%s'" % token.value)
+
+ # rhs (required)
+ rhs = token.value
+
+ def _calculate_index(counter: int, offset_sign: str, offset: int) -> int:
+ """Calculate the index from the counter and offset."""
+ if offset_sign == "-":
+ offset *= -1
+ return counter + offset
+
+ def _format_index(index: int, base: str, width: int) -> str:
+ """Format the index with the given base, and zero-fill it
+ to the given width."""
+ if base in ["d", "o", "x", "X"]:
+ return format(index, base).zfill(width)
+
+ # base can only be n or N here
+ hexa = _format_index(index, "x", width)
+ nibbles = ".".join(hexa[::-1])[:width]
+ if base == "N":
+ nibbles = nibbles.upper()
+ return nibbles
+
+ lmod, lsign, loffset, lwidth, lbase = self._parse_modify(lhs)
+ rmod, rsign, roffset, rwidth, rbase = self._parse_modify(rhs)
+ for i in range(start, stop + 1, step):
+ # +1 because bind is inclusive and python is exclusive
+
+ lindex = _calculate_index(i, lsign, loffset)
+ rindex = _calculate_index(i, rsign, roffset)
+
+ lzfindex = _format_index(lindex, lbase, lwidth)
+ rzfindex = _format_index(rindex, rbase, rwidth)
+
+ name = lhs.replace("$%s" % (lmod), lzfindex)
+ rdata = rhs.replace("$%s" % (rmod), rzfindex)
+
+ self.last_name = dns.name.from_text(
+ name, self.current_origin, self.tok.idna_codec
+ )
+ name = self.last_name
+ if not name.is_subdomain(self.zone_origin):
+ self._eat_line()
+ return
+ if self.relativize:
+ name = name.relativize(self.zone_origin)
+
+ try:
+ rd = dns.rdata.from_text(
+ rdclass,
+ rdtype,
+ rdata,
+ self.current_origin,
+ self.relativize,
+ self.zone_origin,
+ )
+ except dns.exception.SyntaxError:
+ # Catch and reraise.
+ raise
+ except Exception:
+ # All exceptions that occur in the processing of rdata
+ # are treated as syntax errors. This is not strictly
+ # correct, but it is correct almost all of the time.
+ # We convert them to syntax errors so that we can emit
+ # helpful filename:line info.
+ (ty, va) = sys.exc_info()[:2]
+ raise dns.exception.SyntaxError(
+ "caught exception %s: %s" % (str(ty), str(va))
+ )
+
+ self.txn.add(name, ttl, rd)
+
+ def read(self) -> None:
+ """Read a DNS zone file and build a zone object.
+
+ @raises dns.zone.NoSOA: No SOA RR was found at the zone origin
+ @raises dns.zone.NoNS: No NS RRset was found at the zone origin
+ """
+
+ try:
+ while 1:
+ token = self.tok.get(True, True)
+ if token.is_eof():
+ if self.current_file is not None:
+ self.current_file.close()
+ if len(self.saved_state) > 0:
+ (
+ self.tok,
+ self.current_origin,
+ self.last_name,
+ self.current_file,
+ self.last_ttl,
+ self.last_ttl_known,
+ self.default_ttl,
+ self.default_ttl_known,
+ ) = self.saved_state.pop(-1)
+ continue
+ break
+ elif token.is_eol():
+ continue
+ elif token.is_comment():
+ self.tok.get_eol()
+ continue
+ elif token.value[0] == "$" and len(self.allowed_directives) > 0:
+ # Note that we only run directive processing code if at least
+ # one directive is allowed in order to be backwards compatible
+ c = token.value.upper()
+ if c not in self.allowed_directives:
+ raise dns.exception.SyntaxError(
+ f"zone file directive '{c}' is not allowed"
+ )
+ if c == "$TTL":
+ token = self.tok.get()
+ if not token.is_identifier():
+ raise dns.exception.SyntaxError("bad $TTL")
+ self.default_ttl = dns.ttl.from_text(token.value)
+ self.default_ttl_known = True
+ self.tok.get_eol()
+ elif c == "$ORIGIN":
+ self.current_origin = self.tok.get_name()
+ self.tok.get_eol()
+ if self.zone_origin is None:
+ self.zone_origin = self.current_origin
+ self.txn._set_origin(self.current_origin)
+ elif c == "$INCLUDE":
+ token = self.tok.get()
+ filename = token.value
+ token = self.tok.get()
+ new_origin: Optional[dns.name.Name]
+ if token.is_identifier():
+ new_origin = dns.name.from_text(
+ token.value, self.current_origin, self.tok.idna_codec
+ )
+ self.tok.get_eol()
+ elif not token.is_eol_or_eof():
+ raise dns.exception.SyntaxError("bad origin in $INCLUDE")
+ else:
+ new_origin = self.current_origin
+ self.saved_state.append(
+ (
+ self.tok,
+ self.current_origin,
+ self.last_name,
+ self.current_file,
+ self.last_ttl,
+ self.last_ttl_known,
+ self.default_ttl,
+ self.default_ttl_known,
+ )
+ )
+ self.current_file = open(filename, "r")
+ self.tok = dns.tokenizer.Tokenizer(self.current_file, filename)
+ self.current_origin = new_origin
+ elif c == "$GENERATE":
+ self._generate_line()
+ else:
+ raise dns.exception.SyntaxError(
+ f"Unknown zone file directive '{c}'"
+ )
+ continue
+ self.tok.unget(token)
+ self._rr_line()
+ except dns.exception.SyntaxError as detail:
+ (filename, line_number) = self.tok.where()
+ if detail is None:
+ detail = "syntax error"
+ ex = dns.exception.SyntaxError(
+ "%s:%d: %s" % (filename, line_number, detail)
+ )
+ tb = sys.exc_info()[2]
+ raise ex.with_traceback(tb) from None
+
+
+class RRsetsReaderTransaction(dns.transaction.Transaction):
+ def __init__(self, manager, replacement, read_only):
+ assert not read_only
+ super().__init__(manager, replacement, read_only)
+ self.rdatasets = {}
+
+ def _get_rdataset(self, name, rdtype, covers):
+ return self.rdatasets.get((name, rdtype, covers))
+
+ def _get_node(self, name):
+ rdatasets = []
+ for (rdataset_name, _, _), rdataset in self.rdatasets.items():
+ if name == rdataset_name:
+ rdatasets.append(rdataset)
+ if len(rdatasets) == 0:
+ return None
+ node = dns.node.Node()
+ node.rdatasets = rdatasets
+ return node
+
+ def _put_rdataset(self, name, rdataset):
+ self.rdatasets[(name, rdataset.rdtype, rdataset.covers)] = rdataset
+
+ def _delete_name(self, name):
+ # First remove any changes involving the name
+ remove = []
+ for key in self.rdatasets:
+ if key[0] == name:
+ remove.append(key)
+ if len(remove) > 0:
+ for key in remove:
+ del self.rdatasets[key]
+
+ def _delete_rdataset(self, name, rdtype, covers):
+ try:
+ del self.rdatasets[(name, rdtype, covers)]
+ except KeyError:
+ pass
+
+ def _name_exists(self, name):
+ for n, _, _ in self.rdatasets:
+ if n == name:
+ return True
+ return False
+
+ def _changed(self):
+ return len(self.rdatasets) > 0
+
+ def _end_transaction(self, commit):
+ if commit and self._changed():
+ rrsets = []
+ for (name, _, _), rdataset in self.rdatasets.items():
+ rrset = dns.rrset.RRset(
+ name, rdataset.rdclass, rdataset.rdtype, rdataset.covers
+ )
+ rrset.update(rdataset)
+ rrsets.append(rrset)
+ self.manager.set_rrsets(rrsets)
+
+ def _set_origin(self, origin):
+ pass
+
+ def _iterate_rdatasets(self):
+ raise NotImplementedError # pragma: no cover
+
+ def _iterate_names(self):
+ raise NotImplementedError # pragma: no cover
+
+
+class RRSetsReaderManager(dns.transaction.TransactionManager):
+ def __init__(
+ self, origin=dns.name.root, relativize=False, rdclass=dns.rdataclass.IN
+ ):
+ self.origin = origin
+ self.relativize = relativize
+ self.rdclass = rdclass
+ self.rrsets = []
+
+ def reader(self): # pragma: no cover
+ raise NotImplementedError
+
+ def writer(self, replacement=False):
+ assert replacement is True
+ return RRsetsReaderTransaction(self, True, False)
+
+ def get_class(self):
+ return self.rdclass
+
+ def origin_information(self):
+ if self.relativize:
+ effective = dns.name.empty
+ else:
+ effective = self.origin
+ return (self.origin, self.relativize, effective)
+
+ def set_rrsets(self, rrsets):
+ self.rrsets = rrsets
+
+
+def read_rrsets(
+ text: Any,
+ name: Optional[Union[dns.name.Name, str]] = None,
+ ttl: Optional[int] = None,
+ rdclass: Optional[Union[dns.rdataclass.RdataClass, str]] = dns.rdataclass.IN,
+ default_rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
+ rdtype: Optional[Union[dns.rdatatype.RdataType, str]] = None,
+ default_ttl: Optional[Union[int, str]] = None,
+ idna_codec: Optional[dns.name.IDNACodec] = None,
+ origin: Optional[Union[dns.name.Name, str]] = dns.name.root,
+ relativize: bool = False,
+) -> List[dns.rrset.RRset]:
+ """Read one or more rrsets from the specified text, possibly subject
+ to restrictions.
+
+ *text*, a file object or a string, is the input to process.
+
+ *name*, a string, ``dns.name.Name``, or ``None``, is the owner name of
+ the rrset. If not ``None``, then the owner name is "forced", and the
+ input must not specify an owner name. If ``None``, then any owner names
+ are allowed and must be present in the input.
+
+ *ttl*, an ``int``, string, or None. If not ``None``, the the TTL is
+ forced to be the specified value and the input must not specify a TTL.
+ If ``None``, then a TTL may be specified in the input. If it is not
+ specified, then the *default_ttl* will be used.
+
+ *rdclass*, a ``dns.rdataclass.RdataClass``, string, or ``None``. If
+ not ``None``, then the class is forced to the specified value, and the
+ input must not specify a class. If ``None``, then the input may specify
+ a class that matches *default_rdclass*. Note that it is not possible to
+ return rrsets with differing classes; specifying ``None`` for the class
+ simply allows the user to optionally type a class as that may be convenient
+ when cutting and pasting.
+
+ *default_rdclass*, a ``dns.rdataclass.RdataClass`` or string. The class
+ of the returned rrsets.
+
+ *rdtype*, a ``dns.rdatatype.RdataType``, string, or ``None``. If not
+ ``None``, then the type is forced to the specified value, and the
+ input must not specify a type. If ``None``, then a type must be present
+ for each RR.
+
+ *default_ttl*, an ``int``, string, or ``None``. If not ``None``, then if
+ the TTL is not forced and is not specified, then this value will be used.
+ if ``None``, then if the TTL is not forced an error will occur if the TTL
+ is not specified.
+
+ *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
+ encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
+ is used. Note that codecs only apply to the owner name; dnspython does
+ not do IDNA for names in rdata, as there is no IDNA zonefile format.
+
+ *origin*, a string, ``dns.name.Name``, or ``None``, is the origin for any
+ relative names in the input, and also the origin to relativize to if
+ *relativize* is ``True``.
+
+ *relativize*, a bool. If ``True``, names are relativized to the *origin*;
+ if ``False`` then any relative names in the input are made absolute by
+ appending the *origin*.
+ """
+ if isinstance(origin, str):
+ origin = dns.name.from_text(origin, dns.name.root, idna_codec)
+ if isinstance(name, str):
+ name = dns.name.from_text(name, origin, idna_codec)
+ if isinstance(ttl, str):
+ ttl = dns.ttl.from_text(ttl)
+ if isinstance(default_ttl, str):
+ default_ttl = dns.ttl.from_text(default_ttl)
+ if rdclass is not None:
+ rdclass = dns.rdataclass.RdataClass.make(rdclass)
+ else:
+ rdclass = None
+ default_rdclass = dns.rdataclass.RdataClass.make(default_rdclass)
+ if rdtype is not None:
+ rdtype = dns.rdatatype.RdataType.make(rdtype)
+ else:
+ rdtype = None
+ manager = RRSetsReaderManager(origin, relativize, default_rdclass)
+ with manager.writer(True) as txn:
+ tok = dns.tokenizer.Tokenizer(text, "", idna_codec=idna_codec)
+ reader = Reader(
+ tok,
+ default_rdclass,
+ txn,
+ allow_directives=False,
+ force_name=name,
+ force_ttl=ttl,
+ force_rdclass=rdclass,
+ force_rdtype=rdtype,
+ default_ttl=default_ttl,
+ )
+ reader.read()
+ return manager.rrsets
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zonetypes.py b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zonetypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..195ee2ec9b5f62e15d27f196d5f4244f4290f0b4
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dns/zonetypes.py
@@ -0,0 +1,37 @@
+# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
+
+"""Common zone-related types."""
+
+# This is a separate file to avoid import circularity between dns.zone and
+# the implementation of the ZONEMD type.
+
+import hashlib
+
+import dns.enum
+
+
+class DigestScheme(dns.enum.IntEnum):
+ """ZONEMD Scheme"""
+
+ SIMPLE = 1
+
+ @classmethod
+ def _maximum(cls):
+ return 255
+
+
+class DigestHashAlgorithm(dns.enum.IntEnum):
+ """ZONEMD Hash Algorithm"""
+
+ SHA384 = 1
+ SHA512 = 2
+
+ @classmethod
+ def _maximum(cls):
+ return 255
+
+
+_digest_hashers = {
+ DigestHashAlgorithm.SHA384: hashlib.sha384,
+ DigestHashAlgorithm.SHA512: hashlib.sha512,
+}
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..129184e398b0279ace02602aba51ba240210726f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/METADATA
@@ -0,0 +1,147 @@
+Metadata-Version: 2.1
+Name: dnspython
+Version: 2.6.1
+Summary: DNS toolkit
+Project-URL: homepage, https://www.dnspython.org
+Project-URL: repository, https://github.com/rthalley/dnspython.git
+Project-URL: documentation, https://dnspython.readthedocs.io/en/stable/
+Project-URL: issues, https://github.com/rthalley/dnspython/issues
+Author-email: Bob Halley
+License-Expression: ISC
+License-File: LICENSE
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: System Administrators
+Classifier: License :: OSI Approved :: ISC License (ISCL)
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Topic :: Internet :: Name Service (DNS)
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.8
+Provides-Extra: dev
+Requires-Dist: black>=23.1.0; extra == 'dev'
+Requires-Dist: coverage>=7.0; extra == 'dev'
+Requires-Dist: flake8>=7; extra == 'dev'
+Requires-Dist: mypy>=1.8; extra == 'dev'
+Requires-Dist: pylint>=3; extra == 'dev'
+Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
+Requires-Dist: pytest>=7.4; extra == 'dev'
+Requires-Dist: sphinx>=7.2.0; extra == 'dev'
+Requires-Dist: twine>=4.0.0; extra == 'dev'
+Requires-Dist: wheel>=0.42.0; extra == 'dev'
+Provides-Extra: dnssec
+Requires-Dist: cryptography>=41; extra == 'dnssec'
+Provides-Extra: doh
+Requires-Dist: h2>=4.1.0; extra == 'doh'
+Requires-Dist: httpcore>=1.0.0; extra == 'doh'
+Requires-Dist: httpx>=0.26.0; extra == 'doh'
+Provides-Extra: doq
+Requires-Dist: aioquic>=0.9.25; extra == 'doq'
+Provides-Extra: idna
+Requires-Dist: idna>=3.6; extra == 'idna'
+Provides-Extra: trio
+Requires-Dist: trio>=0.23; extra == 'trio'
+Provides-Extra: wmi
+Requires-Dist: wmi>=1.5.1; extra == 'wmi'
+Description-Content-Type: text/markdown
+
+# dnspython
+
+[](https://github.com/rthalley/dnspython/actions/)
+[](https://dnspython.readthedocs.io/en/latest/?badge=latest)
+[](https://badge.fury.io/py/dnspython)
+[](https://opensource.org/licenses/ISC)
+[](https://codecov.io/github/rthalley/dnspython)
+[](https://github.com/psf/black)
+
+## INTRODUCTION
+
+dnspython is a DNS toolkit for Python. It supports almost all record types. It
+can be used for queries, zone transfers, and dynamic updates. It supports TSIG
+authenticated messages and EDNS0.
+
+dnspython provides both high and low level access to DNS. The high level classes
+perform queries for data of a given name, type, and class, and return an answer
+set. The low level classes allow direct manipulation of DNS zones, messages,
+names, and records.
+
+To see a few of the ways dnspython can be used, look in the `examples/`
+directory.
+
+dnspython is a utility to work with DNS, `/etc/hosts` is thus not used. For
+simple forward DNS lookups, it's better to use `socket.getaddrinfo()` or
+`socket.gethostbyname()`.
+
+dnspython originated at Nominum where it was developed
+to facilitate the testing of DNS software.
+
+## ABOUT THIS RELEASE
+
+This is dnspython 2.6.1.
+Please read
+[What's New](https://dnspython.readthedocs.io/en/stable/whatsnew.html) for
+information about the changes in this release.
+
+## INSTALLATION
+
+* Many distributions have dnspython packaged for you, so you should
+ check there first.
+* To use a wheel downloaded from PyPi, run:
+
+ pip install dnspython
+
+* To install from the source code, go into the top-level of the source code
+ and run:
+
+```
+ pip install --upgrade pip build
+ python -m build
+ pip install dist/*.whl
+```
+
+* To install the latest from the master branch, run `pip install git+https://github.com/rthalley/dnspython.git`
+
+Dnspython's default installation does not depend on any modules other than
+those in the Python standard library. To use some features, additional modules
+must be installed. For convenience, pip options are defined for the
+requirements.
+
+If you want to use DNS-over-HTTPS, run
+`pip install dnspython[doh]`.
+
+If you want to use DNSSEC functionality, run
+`pip install dnspython[dnssec]`.
+
+If you want to use internationalized domain names (IDNA)
+functionality, you must run
+`pip install dnspython[idna]`
+
+If you want to use the Trio asynchronous I/O package, run
+`pip install dnspython[trio]`.
+
+If you want to use WMI on Windows to determine the active DNS settings
+instead of the default registry scanning method, run
+`pip install dnspython[wmi]`.
+
+If you want to try the experimental DNS-over-QUIC code, run
+`pip install dnspython[doq]`.
+
+Note that you can install any combination of the above, e.g.:
+`pip install dnspython[doh,dnssec,idna]`
+
+### Notices
+
+Python 2.x support ended with the release of 1.16.0. Dnspython 2.0.0 through
+2.2.x support Python 3.6 and later. For dnspython 2.3.x, the minimum
+supported Python version is 3.7, and for 2.4.x the minimum supported verison is 3.8.
+We plan to align future support with the lifetime of the Python 3 versions.
+
+Documentation has moved to
+[dnspython.readthedocs.io](https://dnspython.readthedocs.io).
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..a4917e062953df5088f8298308a3e671afd72d0f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/RECORD
@@ -0,0 +1,290 @@
+dns/__init__.py,sha256=YJZtDG14Idw5ui3h1nWooSwPM9gsxQgB8M0GBZ3aly0,1663
+dns/__pycache__/__init__.cpython-311.pyc,,
+dns/__pycache__/_asyncbackend.cpython-311.pyc,,
+dns/__pycache__/_asyncio_backend.cpython-311.pyc,,
+dns/__pycache__/_ddr.cpython-311.pyc,,
+dns/__pycache__/_features.cpython-311.pyc,,
+dns/__pycache__/_immutable_ctx.cpython-311.pyc,,
+dns/__pycache__/_trio_backend.cpython-311.pyc,,
+dns/__pycache__/asyncbackend.cpython-311.pyc,,
+dns/__pycache__/asyncquery.cpython-311.pyc,,
+dns/__pycache__/asyncresolver.cpython-311.pyc,,
+dns/__pycache__/dnssec.cpython-311.pyc,,
+dns/__pycache__/dnssectypes.cpython-311.pyc,,
+dns/__pycache__/e164.cpython-311.pyc,,
+dns/__pycache__/edns.cpython-311.pyc,,
+dns/__pycache__/entropy.cpython-311.pyc,,
+dns/__pycache__/enum.cpython-311.pyc,,
+dns/__pycache__/exception.cpython-311.pyc,,
+dns/__pycache__/flags.cpython-311.pyc,,
+dns/__pycache__/grange.cpython-311.pyc,,
+dns/__pycache__/immutable.cpython-311.pyc,,
+dns/__pycache__/inet.cpython-311.pyc,,
+dns/__pycache__/ipv4.cpython-311.pyc,,
+dns/__pycache__/ipv6.cpython-311.pyc,,
+dns/__pycache__/message.cpython-311.pyc,,
+dns/__pycache__/name.cpython-311.pyc,,
+dns/__pycache__/namedict.cpython-311.pyc,,
+dns/__pycache__/nameserver.cpython-311.pyc,,
+dns/__pycache__/node.cpython-311.pyc,,
+dns/__pycache__/opcode.cpython-311.pyc,,
+dns/__pycache__/query.cpython-311.pyc,,
+dns/__pycache__/rcode.cpython-311.pyc,,
+dns/__pycache__/rdata.cpython-311.pyc,,
+dns/__pycache__/rdataclass.cpython-311.pyc,,
+dns/__pycache__/rdataset.cpython-311.pyc,,
+dns/__pycache__/rdatatype.cpython-311.pyc,,
+dns/__pycache__/renderer.cpython-311.pyc,,
+dns/__pycache__/resolver.cpython-311.pyc,,
+dns/__pycache__/reversename.cpython-311.pyc,,
+dns/__pycache__/rrset.cpython-311.pyc,,
+dns/__pycache__/serial.cpython-311.pyc,,
+dns/__pycache__/set.cpython-311.pyc,,
+dns/__pycache__/tokenizer.cpython-311.pyc,,
+dns/__pycache__/transaction.cpython-311.pyc,,
+dns/__pycache__/tsig.cpython-311.pyc,,
+dns/__pycache__/tsigkeyring.cpython-311.pyc,,
+dns/__pycache__/ttl.cpython-311.pyc,,
+dns/__pycache__/update.cpython-311.pyc,,
+dns/__pycache__/version.cpython-311.pyc,,
+dns/__pycache__/versioned.cpython-311.pyc,,
+dns/__pycache__/win32util.cpython-311.pyc,,
+dns/__pycache__/wire.cpython-311.pyc,,
+dns/__pycache__/xfr.cpython-311.pyc,,
+dns/__pycache__/zone.cpython-311.pyc,,
+dns/__pycache__/zonefile.cpython-311.pyc,,
+dns/__pycache__/zonetypes.cpython-311.pyc,,
+dns/_asyncbackend.py,sha256=Ny0kGesm9wbLBnt-0u-tANOKsxcYt2jbMuRoRz_JZUA,2360
+dns/_asyncio_backend.py,sha256=q58xPdqAOLmOYOux8GFRyiH-fSZ7jiwZF-Jg2vHjYSU,8971
+dns/_ddr.py,sha256=rHXKC8kncCTT9N4KBh1flicl79nyDjQ-DDvq30MJ3B8,5247
+dns/_features.py,sha256=MUeyfM_nMYAYkasGfbY7I_15JmwftaZjseuP1L43MT0,2384
+dns/_immutable_ctx.py,sha256=gtoCLMmdHXI23zt5lRSIS3A4Ca3jZJngebdoFFOtiwU,2459
+dns/_trio_backend.py,sha256=Vab_wR2CxDgy2Jz3iM_64FZmP_kMUN9j8LS4eNl-Oig,8269
+dns/asyncbackend.py,sha256=82fXTFls_m7F_ekQbgUGOkoBbs4BI-GBLDZAWNGUvJ0,2796
+dns/asyncquery.py,sha256=Q7u04mbbqCoe9VxsqRcsWTPxgH2Cx49eWWgi2wUyZHU,26850
+dns/asyncresolver.py,sha256=GD86dCyW9YGKs6SggWXwBKEXifW7Qdx4cEAGFKY6fA4,17852
+dns/dnssec.py,sha256=xyYW1cf6eeFNXROrEs1pyY4TgC8jlmUiiootaPbVjjY,40693
+dns/dnssecalgs/__init__.py,sha256=DcnGIbL6m-USPSiLWHSw511awB7dytlljvCOOmzchS0,4279
+dns/dnssecalgs/__pycache__/__init__.cpython-311.pyc,,
+dns/dnssecalgs/__pycache__/base.cpython-311.pyc,,
+dns/dnssecalgs/__pycache__/cryptography.cpython-311.pyc,,
+dns/dnssecalgs/__pycache__/dsa.cpython-311.pyc,,
+dns/dnssecalgs/__pycache__/ecdsa.cpython-311.pyc,,
+dns/dnssecalgs/__pycache__/eddsa.cpython-311.pyc,,
+dns/dnssecalgs/__pycache__/rsa.cpython-311.pyc,,
+dns/dnssecalgs/base.py,sha256=hsFHFr_eCYeDcI0eU6_WiLlOYL0GR4QJ__sXoMrIAfE,2446
+dns/dnssecalgs/cryptography.py,sha256=3uqMfRm-zCkJPOrxUqlu9CmdxIMy71dVor9eAHi0wZM,2425
+dns/dnssecalgs/dsa.py,sha256=hklh_HkT_ZffQBHQ7t6pKUStTH4x5nXlz8R9RUP72aY,3497
+dns/dnssecalgs/ecdsa.py,sha256=GWrJgEXAK08MCdbLk7LQcD2ajKqW_dbONWXh3wieLzw,3016
+dns/dnssecalgs/eddsa.py,sha256=9lQQZ92f2PiIhhylieInO-19aSTDQiyoY8X2kTkGlcs,1914
+dns/dnssecalgs/rsa.py,sha256=jWkhWKByylIo7Y9gAiiO8t8bowF8IZ0siVjgZpdhLSE,3555
+dns/dnssectypes.py,sha256=CyeuGTS_rM3zXr8wD9qMT9jkzvVfTY2JWckUcogG83E,1799
+dns/e164.py,sha256=EsK8cnOtOx7kQ0DmSwibcwkzp6efMWjbRiTyHZO8Q-M,3978
+dns/edns.py,sha256=d8QWhmRd6qlaGfO-tY6iDQZt9XUiyfJfKdjoGjvwOU4,15263
+dns/entropy.py,sha256=qkG8hXDLzrJS6R5My26iA59c0RhPwJNzuOhOCAZU5Bw,4242
+dns/enum.py,sha256=EepaunPKixTSrascy7iAe9UQEXXxP_MB5Gx4jUpHIhg,3691
+dns/exception.py,sha256=FphWy-JLRG06UUUq2VmUGwdPA1xWja_8YfrcffRFlQs,5957
+dns/flags.py,sha256=cQ3kTFyvcKiWHAxI5AwchNqxVOrsIrgJ6brgrH42Wq8,2750
+dns/grange.py,sha256=HA623Mv2mZDmOK_BZNDDakT0L6EHsMQU9lFFkE8dKr0,2148
+dns/immutable.py,sha256=InrtpKvPxl-74oYbzsyneZwAuX78hUqeG22f2aniZbk,2017
+dns/inet.py,sha256=j6jQs3K_ehVhDv-i4jwCKePr5HpEiSzvOXQ4uhgn1sU,5772
+dns/ipv4.py,sha256=qEUXtlqWDH_blicj6VMvyQhfX7-BF0gB_lWJliV-2FI,2552
+dns/ipv6.py,sha256=EyiF5T8t2oww9-W4ZA5Zk2GGnOjTy_uZ50CI7maed_8,6600
+dns/message.py,sha256=DyUtBHArPX-WGj_AtcngyIXZNpLppLZX-6q9TryL_wI,65993
+dns/name.py,sha256=eaR1wVR0rErnD3EPANquCuyqpbxy5VfFVhMenWlBPDE,42672
+dns/namedict.py,sha256=hJRYpKeQv6Bd2LaUOPV0L_a0eXEIuqgggPXaH4c3Tow,4000
+dns/nameserver.py,sha256=VkYRnX5wQ7RihAD6kYqidI_hb9NgKJSAE0GaYulNpHY,9909
+dns/node.py,sha256=NGZa0AUMq-CNledJ6wn1Rx6TFYc703cH2OraLysoNWM,12663
+dns/opcode.py,sha256=I6JyuFUL0msja_BYm6bzXHfbbfqUod_69Ss4xcv8xWQ,2730
+dns/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+dns/query.py,sha256=vB8C5u6HyjPWrEx9kUdTSg3kxrOoWbPGu7brC0eetIM,54832
+dns/quic/__init__.py,sha256=F6BybmRKnMGc4W8nX7K98PeyXiSwy1FHb_bJeA2lQSw,2202
+dns/quic/__pycache__/__init__.cpython-311.pyc,,
+dns/quic/__pycache__/_asyncio.cpython-311.pyc,,
+dns/quic/__pycache__/_common.cpython-311.pyc,,
+dns/quic/__pycache__/_sync.cpython-311.pyc,,
+dns/quic/__pycache__/_trio.cpython-311.pyc,,
+dns/quic/_asyncio.py,sha256=vv4RR3Ol0Y1ZOj7rPAzXxy1UcWjPvhTGQvVkMidPs-o,8159
+dns/quic/_common.py,sha256=06TfauL2VciPYSfrL4gif1eR1rm-TRkQhS2Puuk5URU,7282
+dns/quic/_sync.py,sha256=kE0PRavzd27GPQ9UgYApXZ6SGSW2LwCt8k6XWUvrbVE,8133
+dns/quic/_trio.py,sha256=9zCCBtDs6GAtY_b8ck-A17QMiLZ0njjhVtfFT5qMP7s,7670
+dns/rcode.py,sha256=N6JjrIQjCdJy0boKIp8Hcky5tm__LSDscpDz3rE_sgU,4156
+dns/rdata.py,sha256=9cXM9Y9MK2hy9w5mYqmP-r7_aKjHosigfNn_SfqfGGw,29456
+dns/rdataclass.py,sha256=TK4W4ywB1L_X7EZqk2Gmwnu7vdQpolQF5DtQWyNk5xo,2984
+dns/rdataset.py,sha256=96gTaEIcYEL348VKtTOMAazXBVNtk7m0Xez0mF1eg4I,16756
+dns/rdatatype.py,sha256=gIdYZ0iHRlgiTEO-ftobUANmaAmjTnNc4JljMaP1OnQ,7339
+dns/rdtypes/ANY/AFSDB.py,sha256=k75wMwreF1DAfDymu4lHh16BUx7ulVP3PLeQBZnkurY,1661
+dns/rdtypes/ANY/AMTRELAY.py,sha256=19jfS61mT1CQT-8vf67ZylhDS9JVRVp4WCbFE-7l0jM,3381
+dns/rdtypes/ANY/AVC.py,sha256=SpsXYzlBirRWN0mGnQe0MdN6H8fvlgXPJX5PjOHnEak,1024
+dns/rdtypes/ANY/CAA.py,sha256=AHh59Is-4WiVWd26yovnPM3hXqKS-yx7IWfXSS0NZhE,2511
+dns/rdtypes/ANY/CDNSKEY.py,sha256=bJAdrBMsFHIJz8TF1AxZoNbdxVWBCRTG-bR_uR_r_G4,1225
+dns/rdtypes/ANY/CDS.py,sha256=Y9nIRUCAabztVLbxm2SXAdYapFemCOUuGh5JqroCDUs,1163
+dns/rdtypes/ANY/CERT.py,sha256=2Cu2LQM6-K4darqhHv1EM_blmpYpnrBIIX1GnL_rxKE,3533
+dns/rdtypes/ANY/CNAME.py,sha256=IHGGq2BDpeKUahTr1pvyBQgm0NGBI_vQ3Vs5mKTXO4w,1206
+dns/rdtypes/ANY/CSYNC.py,sha256=KkZ_rG6PfeL14il97nmJGWWmUGGS5o9nd2EqbJqOuYo,2439
+dns/rdtypes/ANY/DLV.py,sha256=J-pOrw5xXsDoaB9G0r6znlYXJtqtcqhsl1OXs6CPRU4,986
+dns/rdtypes/ANY/DNAME.py,sha256=yqXRtx4dAWwB4YCCv-qW6uaxeGhg2LPQ2uyKwWaMdXs,1150
+dns/rdtypes/ANY/DNSKEY.py,sha256=MD8HUVH5XXeAGOnFWg5aVz_w-2tXYwCeVXmzExhiIeQ,1223
+dns/rdtypes/ANY/DS.py,sha256=_gf8vk1O_uY8QXFjsfUw-bny-fm6e-QpCk3PT0JCyoM,995
+dns/rdtypes/ANY/EUI48.py,sha256=x0BkK0sY_tgzuCwfDYpw6tyuChHjjtbRpAgYhO0Y44o,1151
+dns/rdtypes/ANY/EUI64.py,sha256=1jCff2-SXHJLDnNDnMW8Cd_o-ok0P3x6zKy_bcCU5h4,1161
+dns/rdtypes/ANY/GPOS.py,sha256=pM3i6Tn4qwHWOGOuIuW9FENPlSXT_R4xsNJeGrrABc8,4433
+dns/rdtypes/ANY/HINFO.py,sha256=vYGCHGZmYOhtmxHlvPqrK7m4pBg3MSY5herBsKJTbKQ,2249
+dns/rdtypes/ANY/HIP.py,sha256=Ucrnndu3xDyHFB93AVUA3xW-r61GR50kpRHLyLacvZY,3228
+dns/rdtypes/ANY/ISDN.py,sha256=uymYB-ayZSBob6jQgXe4EefNB8-JMLW6VfxXn7ncwPg,2713
+dns/rdtypes/ANY/L32.py,sha256=TMz2kdGCd0siiQZyiocVDCSnvkOdjhUuYRFyf8o622M,1286
+dns/rdtypes/ANY/L64.py,sha256=sb2BjuPA0PQt67nEyT9rBt759C9e6lH71d3EJHGGnww,1592
+dns/rdtypes/ANY/LOC.py,sha256=hLkzgCxqEhg6fn5Uf-DJigKEIE6oavQ8rLpajp3HDLs,12024
+dns/rdtypes/ANY/LP.py,sha256=wTsKIjtK6vh66qZRLSsiE0k54GO8ieVBGZH8dzVvFnE,1338
+dns/rdtypes/ANY/MX.py,sha256=qQk83idY0-SbRMDmB15JOpJi7cSyiheF-ALUD0Ev19E,995
+dns/rdtypes/ANY/NID.py,sha256=N7Xx4kXf3yVAocTlCXQeJ3BtiQNPFPQVdL1iMuyl5W4,1544
+dns/rdtypes/ANY/NINFO.py,sha256=bdL_-6Bejb2EH-xwR1rfSr_9E3SDXLTAnov7x2924FI,1041
+dns/rdtypes/ANY/NS.py,sha256=ThfaPalUlhbyZyNyvBM3k-7onl3eJKq5wCORrOGtkMM,995
+dns/rdtypes/ANY/NSEC.py,sha256=6uRn1SxNuLRNumeoc76BkpECF8ztuqyaYviLjFe7FkQ,2475
+dns/rdtypes/ANY/NSEC3.py,sha256=696h-Zz30bmcT0n1rqoEtS5wqE6jIgsVGzaw5TfdGJo,4331
+dns/rdtypes/ANY/NSEC3PARAM.py,sha256=08p6NWS4DiLav1wOuPbxUxB9MtY2IPjfOMCtJwzzMuA,2635
+dns/rdtypes/ANY/OPENPGPKEY.py,sha256=Va0FGo_8vm1OeX62N5iDTWukAdLwrjTXIZeQ6oanE78,1851
+dns/rdtypes/ANY/OPT.py,sha256=W36RslT_Psp95OPUC70knumOYjKpaRHvGT27I-NV2qc,2561
+dns/rdtypes/ANY/PTR.py,sha256=5HcR1D77Otyk91vVY4tmqrfZfSxSXWyWvwIW-rIH5gc,997
+dns/rdtypes/ANY/RP.py,sha256=5Dgaava9mbLKr87XgbfKZPrunYPBaN8ejNzpmbW6r4s,2184
+dns/rdtypes/ANY/RRSIG.py,sha256=O8vwzS7ldfaj_x8DypvEGFsDSb7al-D7OEnprA3QQoo,4922
+dns/rdtypes/ANY/RT.py,sha256=2t9q3FZQ28iEyceeU25KU2Ur0T5JxELAu8BTwfOUgVw,1013
+dns/rdtypes/ANY/SMIMEA.py,sha256=6yjHuVDfIEodBU9wxbCGCDZ5cWYwyY6FCk-aq2VNU0s,222
+dns/rdtypes/ANY/SOA.py,sha256=Cn8yrag1YvrvwivQgWg-KXmOCaVQVdFHSkFF77w-CE0,3145
+dns/rdtypes/ANY/SPF.py,sha256=rA3Srs9ECQx-37lqm7Zf7aYmMpp_asv4tGS8_fSQ-CU,1022
+dns/rdtypes/ANY/SSHFP.py,sha256=l6TZH2R0kytiZGWez_g-Lq94o5a2xMuwLKwUwsPMx5w,2530
+dns/rdtypes/ANY/TKEY.py,sha256=HjJMIMl4Qb1Nt1JXS6iAymzd2nv_zdLWTt887PJU_5w,4931
+dns/rdtypes/ANY/TLSA.py,sha256=cytzebS3W7FFr9qeJ9gFSHq_bOwUk9aRVlXWHfnVrRs,218
+dns/rdtypes/ANY/TSIG.py,sha256=4fNQJSNWZXUKZejCciwQuUJtTw2g-YbPmqHrEj_pitg,4750
+dns/rdtypes/ANY/TXT.py,sha256=F1U9gIAhwXIV4UVT7CwOCEn_su6G1nJIdgWJsLktk20,1000
+dns/rdtypes/ANY/URI.py,sha256=dpcS8KwcJ2WJ7BkOp4CZYaUyRuw7U2S9GzvVwKUihQg,2921
+dns/rdtypes/ANY/X25.py,sha256=PxjYTKIuoq44LT2S2JHWOV8BOFD0ASqjq0S5VBeGkFM,1944
+dns/rdtypes/ANY/ZONEMD.py,sha256=JQicv69EvUxh4FCT7eZSLzzU5L5brw_dSM65Um2t5lQ,2393
+dns/rdtypes/ANY/__init__.py,sha256=Pox71HfsEnGGB1PGU44pwrrmjxPLQlA-IbX6nQRoA2M,1497
+dns/rdtypes/ANY/__pycache__/AFSDB.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/AMTRELAY.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/AVC.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/CAA.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/CDNSKEY.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/CDS.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/CERT.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/CNAME.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/CSYNC.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/DLV.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/DNAME.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/DNSKEY.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/DS.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/EUI48.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/EUI64.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/GPOS.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/HINFO.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/HIP.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/ISDN.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/L32.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/L64.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/LOC.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/LP.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/MX.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/NID.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/NINFO.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/NS.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/NSEC.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/NSEC3.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/NSEC3PARAM.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/OPENPGPKEY.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/OPT.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/PTR.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/RP.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/RRSIG.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/RT.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/SMIMEA.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/SOA.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/SPF.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/SSHFP.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/TKEY.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/TLSA.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/TSIG.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/TXT.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/URI.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/X25.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/ZONEMD.cpython-311.pyc,,
+dns/rdtypes/ANY/__pycache__/__init__.cpython-311.pyc,,
+dns/rdtypes/CH/A.py,sha256=3S3OhOkSc7_ZsZBVB4GhTS19LPrrZ-yQ8sAp957qEgI,2216
+dns/rdtypes/CH/__init__.py,sha256=GD9YeDKb9VBDo-J5rrChX1MWEGyQXuR9Htnbhg_iYLc,923
+dns/rdtypes/CH/__pycache__/A.cpython-311.pyc,,
+dns/rdtypes/CH/__pycache__/__init__.cpython-311.pyc,,
+dns/rdtypes/IN/A.py,sha256=FfFn3SqbpneL9Ky63COP50V2ZFxqS1ldCKJh39Enwug,1814
+dns/rdtypes/IN/AAAA.py,sha256=AxrOlYy-1TTTWeQypDKeXrDCrdHGor0EKCE4fxzSQGo,1820
+dns/rdtypes/IN/APL.py,sha256=ppyFwn0KYMdyDzphxd0BUhgTmZv0QnDMRLjzQQM793U,5097
+dns/rdtypes/IN/DHCID.py,sha256=zRUh_EOxUPVpJjWY5m7taX8q4Oz5K70785ZtKv5OTCU,1856
+dns/rdtypes/IN/HTTPS.py,sha256=P-IjwcvDQMmtoBgsDHglXF7KgLX73G6jEDqCKsnaGpQ,220
+dns/rdtypes/IN/IPSECKEY.py,sha256=RyIy9K0Yt0uJRjdr6cj5S95ELHHbl--0xV-Qq9O3QQk,3290
+dns/rdtypes/IN/KX.py,sha256=K1JwItL0n5G-YGFCjWeh0C9DyDD8G8VzicsBeQiNAv0,1013
+dns/rdtypes/IN/NAPTR.py,sha256=SaOK-0hIYImwLtb5Hqewi-e49ykJaQiLNvk8ZzNoG7Q,3750
+dns/rdtypes/IN/NSAP.py,sha256=3OUpPOSOxU8fcdi0Oe6Ex2ERXcQ-U3iNf6FftZMtNOw,2165
+dns/rdtypes/IN/NSAP_PTR.py,sha256=iTxlV6fr_Y9lqivLLncSHxEhmFqz5UEElDW3HMBtuCU,1015
+dns/rdtypes/IN/PX.py,sha256=vHDNN2rfLObuUKwpYDIvpPB482BqXlHA-ZQpQn9Sb_E,2756
+dns/rdtypes/IN/SRV.py,sha256=a0zGaUwzvih_a4Q9BViUTFs7NZaCqgl7mls3-KRVHm8,2769
+dns/rdtypes/IN/SVCB.py,sha256=HeFmi2v01F00Hott8FlvQ4R7aPxFmT7RF-gt45R5K_M,218
+dns/rdtypes/IN/WKS.py,sha256=kErSG5AO2qIuot_hkMHnQuZB1_uUzUirNdqBoCp97rk,3652
+dns/rdtypes/IN/__init__.py,sha256=HbI8aw9HWroI6SgEvl8Sx6FdkDswCCXMbSRuJy5o8LQ,1083
+dns/rdtypes/IN/__pycache__/A.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/AAAA.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/APL.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/DHCID.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/HTTPS.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/IPSECKEY.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/KX.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/NAPTR.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/NSAP.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/NSAP_PTR.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/PX.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/SRV.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/SVCB.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/WKS.cpython-311.pyc,,
+dns/rdtypes/IN/__pycache__/__init__.cpython-311.pyc,,
+dns/rdtypes/__init__.py,sha256=NYizfGglJfhqt_GMtSSXf7YQXIEHHCiJ_Y_qaLVeiOI,1073
+dns/rdtypes/__pycache__/__init__.cpython-311.pyc,,
+dns/rdtypes/__pycache__/dnskeybase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/dsbase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/euibase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/mxbase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/nsbase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/svcbbase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/tlsabase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/txtbase.cpython-311.pyc,,
+dns/rdtypes/__pycache__/util.cpython-311.pyc,,
+dns/rdtypes/dnskeybase.py,sha256=FoDllfa9Pz2j2rf45VyUUYUsIt3kjjrwDy6LxrlPb5s,2856
+dns/rdtypes/dsbase.py,sha256=I85Aps1lBsiItdqGpsNY1O8icosfPtkWjiUn1J1lLUQ,3427
+dns/rdtypes/euibase.py,sha256=umN9A3VNw1TziAVtePvUses2jWPcynxINvjgyndPCdQ,2630
+dns/rdtypes/mxbase.py,sha256=DzjbiKoAAgpqbhwMBIFGA081jR5_doqGAq-kLvy2mns,3196
+dns/rdtypes/nsbase.py,sha256=tueXVV6E8lelebOmrmoOPq47eeRvOpsxHVXH4cOFxcs,2323
+dns/rdtypes/svcbbase.py,sha256=TQRT52m8F2NpSJsHUkTFS-hrkyhcIoAodW6bBHED4CY,16674
+dns/rdtypes/tlsabase.py,sha256=pIiWem6sF4IwyyKmyqx5xg55IG0w3K9r502Yx8PdziA,2596
+dns/rdtypes/txtbase.py,sha256=K4v2ulFu0DxPjxyf_Ul7YRjfBpUO-Ay_ChnR_Wx-ywA,3601
+dns/rdtypes/util.py,sha256=6AGQ-k3mLNlx4Ep_FiDABj1WVumUUGs3zQ6X-2iISec,9003
+dns/renderer.py,sha256=5THf1iKql2JPL2sKZt2-b4zqHKfk_vlx0FEfPtMJysY,11254
+dns/resolver.py,sha256=wagpUIu8Oh12O-zk48U30A6VQQOspjfibU4Ls2So-kM,73552
+dns/reversename.py,sha256=zoqXEbMZXm6R13nXbJHgTsf6L2C6uReODj6mqSHrTiE,3828
+dns/rrset.py,sha256=J-oQPEPJuKueLLiz1FN08P-ys9fjHhPWuwpDdrL4UTQ,9170
+dns/serial.py,sha256=-t5rPW-TcJwzBMfIJo7Tl-uDtaYtpqOfCVYx9dMaDCY,3606
+dns/set.py,sha256=Lr1qhyqywoobNkj9sAfdovoFy9vBfkz2eHdTCc7sZRs,9088
+dns/tokenizer.py,sha256=Dcc3lQgEIHCVZBuO6FaKWEojtPSd3EuaUC4vQA-spnk,23583
+dns/transaction.py,sha256=ZlnDT-V4W01J3cS501GaRLVhE9t1jZdnEZxPyZ0Cvg4,22636
+dns/tsig.py,sha256=I-Y-c3WMBX11bVioy5puFly2BhlpptUz82ikahxuh1c,11413
+dns/tsigkeyring.py,sha256=Z0xZemcU3XjZ9HlxBYv2E2PSuIhaFreqLDlD7HcmZDA,2633
+dns/ttl.py,sha256=fWFkw8qfk6saTp7lAPxZOuD3U3TRxVRvIpljQnG-01I,2979
+dns/update.py,sha256=y9d6LOO8xrUaH2UrZhy3ssnx8bJEsxqTArw5V8XqBRs,12243
+dns/version.py,sha256=sRMqE5tzPhXEzz-SEvdN82pP77xF_i1iELxaJN0roDE,1926
+dns/versioned.py,sha256=3YQj8mzGmZEsjnuVJJjcWopVmDKYLhEj4hEGTLEwzco,11765
+dns/win32util.py,sha256=NEjd5RXQU2aV1WsBMoIGZmXyqqKCxS4WYq9HqFQoVig,9107
+dns/wire.py,sha256=vy0SolgECbO1UXB4dnhXhDeFKOJT29nQxXvSfKOgA5s,2830
+dns/xfr.py,sha256=FKkKO-kSpyE1vHU5mnoPIP4YxiCl5gG7E5wOgY_4GO8,13273
+dns/zone.py,sha256=lLAarSxPtpx4Sw29OQ0ifPshD4QauGu8RnPh2dEropA,52086
+dns/zonefile.py,sha256=9pgkO0pV8Js53Oq9ZKOSbpFkGS5r_orU-25tmufGP9M,27929
+dns/zonetypes.py,sha256=HrQNZxZ_gWLWI9dskix71msi9wkYK5pgrBBbPb1T74Y,690
+dnspython-2.6.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+dnspython-2.6.1.dist-info/METADATA,sha256=2GJFv-NqkwIytog5VQe0wPtZKoS016uyYfG76lqftto,5808
+dnspython-2.6.1.dist-info/RECORD,,
+dnspython-2.6.1.dist-info/WHEEL,sha256=TJPnKdtrSue7xZ_AVGkp9YXcvDrobsjBds1du3Nx6dc,87
+dnspython-2.6.1.dist-info/licenses/LICENSE,sha256=w-o_9WVLMpwZ07xfdIGvYjw93tSmFFWFSZ-EOtPXQc0,1526
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..5998f3aab327ceb8cb346647a3461e220359aebf
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/dnspython-2.6.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.21.1
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/docs/conf.py b/pgsql/pgAdmin 4/python/Lib/site-packages/docs/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0f24b5efeb7da84958bb73347407d96c2e10ab8
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/docs/conf.py
@@ -0,0 +1,384 @@
+# -*- coding: utf-8 -*-
+# Copyright 2023 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# google-auth-oauthlib documentation build configuration file
+#
+# This file is execfile()d with the current directory set to its
+# containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys
+import os
+import shlex
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+sys.path.insert(0, os.path.abspath(".."))
+
+# For plugins that can not read conf.py.
+# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85
+sys.path.insert(0, os.path.abspath("."))
+
+__version__ = ""
+
+# -- General configuration ------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+needs_sphinx = "1.5.5"
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ "sphinx.ext.autodoc",
+ "sphinx.ext.autosummary",
+ "sphinx.ext.intersphinx",
+ "sphinx.ext.coverage",
+ "sphinx.ext.doctest",
+ "sphinx.ext.napoleon",
+ "sphinx.ext.todo",
+ "sphinx.ext.viewcode",
+ "recommonmark",
+]
+
+# autodoc/autosummary flags
+autoclass_content = "both"
+autodoc_default_options = {"members": True}
+autosummary_generate = True
+
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ["_templates"]
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+# source_suffix = ['.rst', '.md']
+source_suffix = [".rst", ".md"]
+
+# The encoding of source files.
+# source_encoding = 'utf-8-sig'
+
+# The root toctree document.
+root_doc = "index"
+
+# General information about the project.
+project = "google-auth-oauthlib"
+copyright = "2019, Google"
+author = "Google APIs"
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The full version, including alpha/beta/rc tags.
+release = __version__
+# The short X.Y version.
+version = ".".join(release.split(".")[0:2])
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+# today = ''
+# Else, today_fmt is used as the format for a strftime call.
+# today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = [
+ "_build",
+ "**/.nox/**/*",
+ "samples/AUTHORING_GUIDE.md",
+ "samples/CONTRIBUTING.md",
+ "samples/snippets/README.rst",
+]
+
+# The reST default role (used for this markup: `text`) to use for all
+# documents.
+# default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+# add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+# add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+# show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = "sphinx"
+
+# A list of ignored prefixes for module index sorting.
+# modindex_common_prefix = []
+
+# If true, keep warnings as "system message" paragraphs in the built documents.
+# keep_warnings = False
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = True
+
+
+# -- Options for HTML output ----------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = "alabaster"
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+html_theme_options = {
+ "description": "Google Cloud Client Libraries for google-auth-oauthlib",
+ "github_user": "googleapis",
+ "github_repo": "google-auth-library-python-oauthlib",
+ "github_banner": True,
+ "font_family": "'Roboto', Georgia, sans",
+ "head_font_family": "'Roboto', Georgia, serif",
+ "code_font_family": "'Roboto Mono', 'Consolas', monospace",
+}
+
+# Add any paths that contain custom themes here, relative to this directory.
+# html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# " v documentation".
+# html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+# html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+# html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+# html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ["_static"]
+
+# Add any extra paths that contain custom files (such as robots.txt or
+# .htaccess) here, relative to this directory. These files are copied
+# directly to the root of the documentation.
+# html_extra_path = []
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+# html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+# html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+# html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+# html_additional_pages = {}
+
+# If false, no module index is generated.
+# html_domain_indices = True
+
+# If false, no index is generated.
+# html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+# html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+# html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+# html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+# html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+# html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+# html_file_suffix = None
+
+# Language to be used for generating the HTML full-text search index.
+# Sphinx supports the following languages:
+# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
+# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
+# html_search_language = 'en'
+
+# A dictionary with options for the search language support, empty by default.
+# Now only 'ja' uses this config value
+# html_search_options = {'type': 'default'}
+
+# The name of a javascript file (relative to the configuration directory) that
+# implements a search results scorer. If empty, the default will be used.
+# html_search_scorer = 'scorer.js'
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = "google-auth-oauthlib-doc"
+
+# -- Options for warnings ------------------------------------------------------
+
+
+suppress_warnings = [
+ # Temporarily suppress this to avoid "more than one target found for
+ # cross-reference" warning, which are intractable for us to avoid while in
+ # a mono-repo.
+ # See https://github.com/sphinx-doc/sphinx/blob
+ # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843
+ "ref.python"
+]
+
+# -- Options for LaTeX output ---------------------------------------------
+
+latex_elements = {
+ # The paper size ('letterpaper' or 'a4paper').
+ #'papersize': 'letterpaper',
+ # The font size ('10pt', '11pt' or '12pt').
+ #'pointsize': '10pt',
+ # Additional stuff for the LaTeX preamble.
+ #'preamble': '',
+ # Latex figure (float) alignment
+ #'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+# author, documentclass [howto, manual, or own class]).
+latex_documents = [
+ (
+ root_doc,
+ "google-auth-oauthlib.tex",
+ "google-auth-oauthlib Documentation",
+ author,
+ "manual",
+ )
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+# latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+# latex_use_parts = False
+
+# If true, show page references after internal links.
+# latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+# latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+# latex_appendices = []
+
+# If false, no module index is generated.
+# latex_domain_indices = True
+
+
+# -- Options for manual page output ---------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ (
+ root_doc,
+ "google-auth-oauthlib",
+ "google-auth-oauthlib Documentation",
+ [author],
+ 1,
+ )
+]
+
+# If true, show URL addresses after external links.
+# man_show_urls = False
+
+
+# -- Options for Texinfo output -------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ (
+ root_doc,
+ "google-auth-oauthlib",
+ "google-auth-oauthlib Documentation",
+ author,
+ "google-auth-oauthlib",
+ "google-auth-oauthlib Library",
+ "APIs",
+ )
+]
+
+# Documents to append as an appendix to all manuals.
+# texinfo_appendices = []
+
+# If false, no module index is generated.
+# texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+# texinfo_show_urls = 'footnote'
+
+# If true, do not generate a @detailmenu in the "Top" node's menu.
+# texinfo_no_detailmenu = False
+
+
+# Example configuration for intersphinx: refer to the Python standard library.
+intersphinx_mapping = {
+ "python": ("https://python.readthedocs.org/en/latest/", None),
+ "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None),
+ "google.api_core": (
+ "https://googleapis.dev/python/google-api-core/latest/",
+ None,
+ ),
+ "grpc": ("https://grpc.github.io/grpc/python/", None),
+ "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None),
+ "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None),
+}
+
+
+# Napoleon settings
+napoleon_google_docstring = True
+napoleon_numpy_docstring = True
+napoleon_include_private_with_doc = False
+napoleon_include_special_with_doc = True
+napoleon_use_admonition_for_examples = False
+napoleon_use_admonition_for_notes = False
+napoleon_use_admonition_for_references = False
+napoleon_use_ivar = False
+napoleon_use_param = True
+napoleon_use_rtype = True
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..122e7a71fcd85a909f2321cda3d4b8495b913c80
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/LICENSE
@@ -0,0 +1,27 @@
+This is free and unencumbered software released into the public
+domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a
+compiled binary, for any purpose, commercial or non-commercial,
+and by any means.
+
+In jurisdictions that recognize copyright laws, the author or
+authors of this software dedicate any and all copyright
+interest in the software to the public domain. We make this
+dedication for the benefit of the public at large and to the
+detriment of our heirs and successors. We intend this
+dedication to be an overt act of relinquishment in perpetuity
+of all present and future rights to this software under
+copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+For more information, please refer to
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..a584e7826f06f49bd5db4aec2e9e483c74fa0162
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/METADATA
@@ -0,0 +1,486 @@
+Metadata-Version: 2.1
+Name: email_validator
+Version: 2.1.1
+Summary: A robust email address syntax and deliverability validation library.
+Home-page: https://github.com/JoshData/python-email-validator
+Author: Joshua Tauberer
+Author-email: jt@occams.info
+License: Unlicense
+Keywords: email address validator
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: dnspython >=2.0.0
+Requires-Dist: idna >=2.0.0
+
+email-validator: Validate Email Addresses
+=========================================
+
+A robust email address syntax and deliverability validation library for
+Python 3.8+ by [Joshua Tauberer](https://joshdata.me).
+
+This library validates that a string is of the form `name@example.com`
+and optionally checks that the domain name is set up to receive email.
+This is the sort of validation you would want when you are identifying
+users by their email address like on a registration/login form (but not
+necessarily for composing an email message, see below).
+
+Key features:
+
+* Checks that an email address has the correct syntax --- great for
+ email-based registration/login forms or validing data.
+* Gives friendly English error messages when validation fails that you
+ can display to end-users.
+* Checks deliverability (optional): Does the domain name resolve?
+ (You can override the default DNS resolver to add query caching.)
+* Supports internationalized domain names and internationalized local parts.
+* Rejects addresses with unsafe Unicode characters, obsolete email address
+ syntax that you'd find unexpected, special use domain names like
+ `@localhost`, and domains without a dot by default. This is an
+ opinionated library!
+* Normalizes email addresses (important for internationalized
+ and quoted-string addresses! see below).
+* Python type annotations are used.
+
+This is an opinionated library. You should definitely also consider using
+the less-opinionated [pyIsEmail](https://github.com/michaelherold/pyIsEmail) and
+[flanker](https://github.com/mailgun/flanker) if they are better for your
+use case.
+
+[](https://github.com/JoshData/python-email-validator/actions/workflows/test_and_build.yaml)
+
+View the [CHANGELOG / Release Notes](CHANGELOG.md) for the version history of changes in the library. Occasionally this README is ahead of the latest published package --- see the CHANGELOG for details.
+
+---
+
+Installation
+------------
+
+This package [is on PyPI](https://pypi.org/project/email-validator/), so:
+
+```sh
+pip install email-validator
+```
+
+(You might need to use `pip3` depending on your local environment.)
+
+Quick Start
+-----------
+
+If you're validating a user's email address before creating a user
+account in your application, you might do this:
+
+```python
+from email_validator import validate_email, EmailNotValidError
+
+email = "my+address@example.org"
+
+try:
+
+ # Check that the email address is valid. Turn on check_deliverability
+ # for first-time validations like on account creation pages (but not
+ # login pages).
+ emailinfo = validate_email(email, check_deliverability=False)
+
+ # After this point, use only the normalized form of the email address,
+ # especially before going to a database query.
+ email = emailinfo.normalized
+
+except EmailNotValidError as e:
+
+ # The exception message is human-readable explanation of why it's
+ # not a valid (or deliverable) email address.
+ print(str(e))
+```
+
+This validates the address and gives you its normalized form. You should
+**put the normalized form in your database** and always normalize before
+checking if an address is in your database. When using this in a login form,
+set `check_deliverability` to `False` to avoid unnecessary DNS queries.
+
+Usage
+-----
+
+### Overview
+
+The module provides a function `validate_email(email_address)` which
+takes an email address and:
+
+- Raises a `EmailNotValidError` with a helpful, human-readable error
+ message explaining why the email address is not valid, or
+- Returns an object with a normalized form of the email address (which
+ you should use!) and other information about it.
+
+When an email address is not valid, `validate_email` raises either an
+`EmailSyntaxError` if the form of the address is invalid or an
+`EmailUndeliverableError` if the domain name fails DNS checks. Both
+exception classes are subclasses of `EmailNotValidError`, which in turn
+is a subclass of `ValueError`.
+
+But when an email address is valid, an object is returned containing
+a normalized form of the email address (which you should use!) and
+other information.
+
+The validator doesn't, by default, permit obsoleted forms of email addresses
+that no one uses anymore even though they are still valid and deliverable, since
+they will probably give you grief if you're using email for login. (See
+later in the document about how to allow some obsolete forms.)
+
+The validator optionally checks that the domain name in the email address has
+a DNS MX record indicating that it can receive email. (Except a Null MX record.
+If there is no MX record, a fallback A/AAAA-record is permitted, unless
+a reject-all SPF record is present.) DNS is slow and sometimes unavailable or
+unreliable, so consider whether these checks are useful for your use case and
+turn them off if they aren't.
+There is nothing to be gained by trying to actually contact an SMTP server, so
+that's not done here. For privacy, security, and practicality reasons, servers
+are good at not giving away whether an address is
+deliverable or not: email addresses that appear to accept mail at first
+can bounce mail after a delay, and bounced mail may indicate a temporary
+failure of a good email address (sometimes an intentional failure, like
+greylisting).
+
+### Options
+
+The `validate_email` function also accepts the following keyword arguments
+(defaults are as shown below):
+
+`check_deliverability=True`: If true, DNS queries are made to check that the domain name in the email address (the part after the @-sign) can receive mail, as described above. Set to `False` to skip this DNS-based check. It is recommended to pass `False` when performing validation for login pages (but not account creation pages) since re-validation of a previously validated domain in your database by querying DNS at every login is probably undesirable. You can also set `email_validator.CHECK_DELIVERABILITY` to `False` to turn this off for all calls by default.
+
+`dns_resolver=None`: Pass an instance of [dns.resolver.Resolver](https://dnspython.readthedocs.io/en/latest/resolver-class.html) to control the DNS resolver including setting a timeout and [a cache](https://dnspython.readthedocs.io/en/latest/resolver-caching.html). The `caching_resolver` function shown below is a helper function to construct a dns.resolver.Resolver with a [LRUCache](https://dnspython.readthedocs.io/en/latest/resolver-caching.html#dns.resolver.LRUCache). Reuse the same resolver instance across calls to `validate_email` to make use of the cache.
+
+`test_environment=False`: If `True`, DNS-based deliverability checks are disabled and `test` and `**.test` domain names are permitted (see below). You can also set `email_validator.TEST_ENVIRONMENT` to `True` to turn it on for all calls by default.
+
+`allow_smtputf8=True`: Set to `False` to prohibit internationalized addresses that would
+ require the
+ [SMTPUTF8](https://tools.ietf.org/html/rfc6531) extension. You can also set `email_validator.ALLOW_SMTPUTF8` to `False` to turn it off for all calls by default.
+
+`allow_quoted_local=False`: Set to `True` to allow obscure and potentially problematic email addresses in which the part of the address before the @-sign contains spaces, @-signs, or other surprising characters when the local part is surrounded in quotes (so-called quoted-string local parts). In the object returned by `validate_email`, the normalized local part removes any unnecessary backslash-escaping and even removes the surrounding quotes if the address would be valid without them. You can also set `email_validator.ALLOW_QUOTED_LOCAL` to `True` to turn this on for all calls by default.
+
+`allow_domain_literal=False`: Set to `True` to allow bracketed IPv4 and "IPv6:"-prefixd IPv6 addresses in the domain part of the email address. No deliverability checks are performed for these addresses. In the object returned by `validate_email`, the normalized domain will use the condensed IPv6 format, if applicable. The object's `domain_address` attribute will hold the parsed `ipaddress.IPv4Address` or `ipaddress.IPv6Address` object if applicable. You can also set `email_validator.ALLOW_DOMAIN_LITERAL` to `True` to turn this on for all calls by default.
+
+`allow_empty_local=False`: Set to `True` to allow an empty local part (i.e.
+ `@example.com`), e.g. for validating Postfix aliases.
+
+
+### DNS timeout and cache
+
+When validating many email addresses or to control the timeout (the default is 15 seconds), create a caching [dns.resolver.Resolver](https://dnspython.readthedocs.io/en/latest/resolver-class.html) to reuse in each call. The `caching_resolver` function returns one easily for you:
+
+```python
+from email_validator import validate_email, caching_resolver
+
+resolver = caching_resolver(timeout=10)
+
+while True:
+ validate_email(email, dns_resolver=resolver)
+```
+
+### Test addresses
+
+This library rejects email addresses that use the [Special Use Domain Names](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml) `invalid`, `localhost`, `test`, and some others by raising `EmailSyntaxError`. This is to protect your system from abuse: You probably don't want a user to be able to cause an email to be sent to `localhost` (although they might be able to still do so via a malicious MX record). However, in your non-production test environments you may want to use `@test` or `@myname.test` email addresses. There are three ways you can allow this:
+
+1. Add `test_environment=True` to the call to `validate_email` (see above).
+2. Set `email_validator.TEST_ENVIRONMENT` to `True` globally.
+3. Remove the special-use domain name that you want to use from `email_validator.SPECIAL_USE_DOMAIN_NAMES`, e.g.:
+
+```python
+import email_validator
+email_validator.SPECIAL_USE_DOMAIN_NAMES.remove("test")
+```
+
+It is tempting to use `@example.com/net/org` in tests. They are *not* in this library's `SPECIAL_USE_DOMAIN_NAMES` list so you can, but shouldn't, use them. These domains are reserved to IANA for use in documentation so there is no risk of accidentally emailing someone at those domains. But beware that this library will nevertheless reject these domain names if DNS-based deliverability checks are not disabled because these domains do not resolve to domains that accept email. In tests, consider using your own domain name or `@test` or `@myname.test` instead.
+
+Internationalized email addresses
+---------------------------------
+
+The email protocol SMTP and the domain name system DNS have historically
+only allowed English (ASCII) characters in email addresses and domain names,
+respectively. Each has adapted to internationalization in a separate
+way, creating two separate aspects to email address
+internationalization.
+
+### Internationalized domain names (IDN)
+
+The first is [internationalized domain names (RFC
+5891)](https://tools.ietf.org/html/rfc5891), a.k.a IDNA 2008. The DNS
+system has not been updated with Unicode support. Instead, internationalized
+domain names are converted into a special IDNA ASCII "[Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt)"
+form starting with `xn--`. When an email address has non-ASCII
+characters in its domain part, the domain part is replaced with its IDNA
+ASCII equivalent form in the process of mail transmission. Your mail
+submission library probably does this for you transparently. ([Compliance
+around the web is not very good though](http://archives.miloush.net/michkap/archive/2012/02/27/10273315.html).) This library conforms to IDNA 2008
+using the [idna](https://github.com/kjd/idna) module by Kim Davies.
+
+### Internationalized local parts
+
+The second sort of internationalization is internationalization in the
+*local* part of the address (before the @-sign). In non-internationalized
+email addresses, only English letters, numbers, and some punctuation
+(`._!#$%&'^``*+-=~/?{|}`) are allowed. In internationalized email address
+local parts, a wider range of Unicode characters are allowed.
+
+A surprisingly large number of Unicode characters are not safe to display,
+especially when the email address is concatenated with other text, so this
+library tries to protect you by not permitting reserved, non-, private use,
+formatting (which can be used to alter the display order of characters),
+whitespace, and control characters, and combining characters
+as the first character of the local part and the domain name (so that they
+cannot combine with something outside of the email address string or with
+the @-sign). See https://qntm.org/safe and https://trojansource.codes/
+for relevant prior work. (Other than whitespace, these are checks that
+you should be applying to nearly all user inputs in a security-sensitive
+context.)
+
+These character checks are performed after Unicode normalization (see below),
+so you are only fully protected if you replace all user-provided email addresses
+with the normalized email address string returned by this library. This does not
+guard against the well known problem that many Unicode characters look alike
+(or are identical), which can be used to fool humans reading displayed text.
+
+Email addresses with these non-ASCII characters require that your mail
+submission library and the mail servers along the route to the destination,
+including your own outbound mail server, all support the
+[SMTPUTF8 (RFC 6531)](https://tools.ietf.org/html/rfc6531) extension.
+Support for SMTPUTF8 varies. See the `allow_smtputf8` parameter.
+
+### If you know ahead of time that SMTPUTF8 is not supported by your mail submission stack
+
+By default all internationalized forms are accepted by the validator.
+But if you know ahead of time that SMTPUTF8 is not supported by your
+mail submission stack, then you must filter out addresses that require
+SMTPUTF8 using the `allow_smtputf8=False` keyword argument (see above).
+This will cause the validation function to raise a `EmailSyntaxError` if
+delivery would require SMTPUTF8. That's just in those cases where
+non-ASCII characters appear before the @-sign. If you do not set
+`allow_smtputf8=False`, you can also check the value of the `smtputf8`
+field in the returned object.
+
+If your mail submission library doesn't support Unicode at all --- even
+in the domain part of the address --- then immediately prior to mail
+submission you must replace the email address with its ASCII-ized form.
+This library gives you back the ASCII-ized form in the `ascii_email`
+field in the returned object, which you can get like this:
+
+```python
+emailinfo = validate_email(email, allow_smtputf8=False)
+email = emailinfo.ascii_email
+```
+
+The local part is left alone (if it has internationalized characters
+`allow_smtputf8=False` will force validation to fail) and the domain
+part is converted to [IDNA ASCII](https://tools.ietf.org/html/rfc5891).
+(You probably should not do this at account creation time so you don't
+change the user's login information without telling them.)
+
+Normalization
+-------------
+
+### Unicode Normalization
+
+The use of Unicode in email addresses introduced a normalization
+problem. Different Unicode strings can look identical and have the same
+semantic meaning to the user. The `normalized` field returned on successful
+validation provides the correctly normalized form of the given email
+address.
+
+For example, the CJK fullwidth Latin letters are considered semantically
+equivalent in domain names to their ASCII counterparts. This library
+normalizes them to their ASCII counterparts:
+
+```python
+emailinfo = validate_email("me@Domain.com")
+print(emailinfo.normalized)
+print(emailinfo.ascii_email)
+# prints "me@domain.com" twice
+```
+
+Because an end-user might type their email address in different (but
+equivalent) un-normalized forms at different times, you ought to
+replace what they enter with the normalized form immediately prior to
+going into your database (during account creation), querying your database
+(during login), or sending outbound mail. Normalization may also change
+the length of an email address, and this may affect whether it is valid
+and acceptable by your SMTP provider.
+
+The normalizations include lowercasing the domain part of the email
+address (domain names are case-insensitive), [Unicode "NFC"
+normalization](https://en.wikipedia.org/wiki/Unicode_equivalence) of the
+whole address (which turns characters plus [combining
+characters](https://en.wikipedia.org/wiki/Combining_character) into
+precomposed characters where possible, replacement of [fullwidth and
+halfwidth
+characters](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms)
+in the domain part, possibly other
+[UTS46](http://unicode.org/reports/tr46) mappings on the domain part,
+and conversion from Punycode to Unicode characters.
+
+(See [RFC 6532 (internationalized email) section
+3.1](https://tools.ietf.org/html/rfc6532#section-3.1) and [RFC 5895
+(IDNA 2008) section 2](http://www.ietf.org/rfc/rfc5895.txt).)
+
+### Other Normalization
+
+Normalization is also applied to quoted-string local parts and domain
+literal IPv6 addresses if you have allowed them by the `allow_quoted_local`
+and `allow_domain_literal` options. In quoted-string local parts, unnecessary
+backslash escaping is removed and even the surrounding quotes are removed if
+they are unnecessary. For IPv6 domain literals, the IPv6 address is
+normalized to condensed form. [RFC 2142](https://datatracker.ietf.org/doc/html/rfc2142)
+also requires lowercase normalization for some specific mailbox names like `postmaster@`.
+
+### Length checks
+
+This library checks that the length of the email address is not longer than
+the maximum length. The check is performed on the normalized form of the
+address, which might be different from a string provided by a user. If you
+send email to the original string and not the normalized address, the email
+might be rejected because the original address could be too long.
+
+Examples
+--------
+
+For the email address `test@joshdata.me`, the returned object is:
+
+```python
+ValidatedEmail(
+ normalized='test@joshdata.me',
+ local_part='test',
+ domain='joshdata.me',
+ ascii_email='test@joshdata.me',
+ ascii_local_part='test',
+ ascii_domain='joshdata.me',
+ smtputf8=False)
+```
+
+For the fictitious but valid address `example@ツ.ⓁⒾⒻⒺ`, which has an
+internationalized domain but ASCII local part, the returned object is:
+
+```python
+ValidatedEmail(
+ normalized='example@ツ.life',
+ local_part='example',
+ domain='ツ.life',
+ ascii_email='example@xn--bdk.life',
+ ascii_local_part='example',
+ ascii_domain='xn--bdk.life',
+ smtputf8=False)
+
+```
+
+Note that `normalized` and other fields provide a normalized form of the
+email address, domain name, and (in other cases) local part (see earlier
+discussion of normalization), which you should use in your database.
+
+Calling `validate_email` with the ASCII form of the above email address,
+`example@xn--bdk.life`, returns the exact same information (i.e., the
+`normalized` field always will contain Unicode characters, not Punycode).
+
+For the fictitious address `ツ-test@joshdata.me`, which has an
+internationalized local part, the returned object is:
+
+```python
+ValidatedEmail(
+ normalized='ツ-test@joshdata.me',
+ local_part='ツ-test',
+ domain='joshdata.me',
+ ascii_email=None,
+ ascii_local_part=None,
+ ascii_domain='joshdata.me',
+ smtputf8=True)
+```
+
+Now `smtputf8` is `True` and `ascii_email` is `None` because the local
+part of the address is internationalized. The `local_part` and `normalized` fields
+return the normalized form of the address.
+
+Return value
+------------
+
+When an email address passes validation, the fields in the returned object
+are:
+
+| Field | Value |
+| -----:|-------|
+| `normalized` | The normalized form of the email address that you should put in your database. This combines the `local_part` and `domain` fields (see below). |
+| `ascii_email` | If set, an ASCII-only form of the normalized email address by replacing the domain part with [IDNA](https://tools.ietf.org/html/rfc5891) [Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt). This field will be present when an ASCII-only form of the email address exists (including if the email address is already ASCII). If the local part of the email address contains internationalized characters, `ascii_email` will be `None`. If set, it merely combines `ascii_local_part` and `ascii_domain`. |
+| `local_part` | The normalized local part of the given email address (before the @-sign). Normalization includes Unicode NFC normalization and removing unnecessary quoted-string quotes and backslashes. If `allow_quoted_local` is True and the surrounding quotes are necessary, the quotes _will_ be present in this field. |
+| `ascii_local_part` | If set, the local part, which is composed of ASCII characters only. |
+| `domain` | The canonical internationalized Unicode form of the domain part of the email address. If the returned string contains non-ASCII characters, either the [SMTPUTF8](https://tools.ietf.org/html/rfc6531) feature of your mail relay will be required to transmit the message or else the email address's domain part must be converted to IDNA ASCII first: Use `ascii_domain` field instead. |
+| `ascii_domain` | The [IDNA](https://tools.ietf.org/html/rfc5891) [Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt)-encoded form of the domain part of the given email address, as it would be transmitted on the wire. |
+| `domain_address` | If domain literals are allowed and if the email address contains one, an `ipaddress.IPv4Address` or `ipaddress.IPv6Address` object. |
+| `smtputf8` | A boolean indicating that the [SMTPUTF8](https://tools.ietf.org/html/rfc6531) feature of your mail relay will be required to transmit messages to this address because the local part of the address has non-ASCII characters (the local part cannot be IDNA-encoded). If `allow_smtputf8=False` is passed as an argument, this flag will always be false because an exception is raised if it would have been true. |
+| `mx` | A list of (priority, domain) tuples of MX records specified in the DNS for the domain (see [RFC 5321 section 5](https://tools.ietf.org/html/rfc5321#section-5)). May be `None` if the deliverability check could not be completed because of a temporary issue like a timeout. |
+| `mx_fallback_type` | `None` if an `MX` record is found. If no MX records are actually specified in DNS and instead are inferred, through an obsolete mechanism, from A or AAAA records, the value is the type of DNS record used instead (`A` or `AAAA`). May be `None` if the deliverability check could not be completed because of a temporary issue like a timeout. |
+| `spf` | Any SPF record found while checking deliverability. Only set if the SPF record is queried. |
+
+Assumptions
+-----------
+
+By design, this validator does not pass all email addresses that
+strictly conform to the standards. Many email address forms are obsolete
+or likely to cause trouble:
+
+* The validator assumes the email address is intended to be
+ usable on the public Internet. The domain part
+ of the email address must be a resolvable domain name
+ (see the deliverability checks described above).
+ Most [Special Use Domain Names](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml)
+ and their subdomains, as well as
+ domain names without a `.`, are rejected as a syntax error
+ (except see the `test_environment` parameter above).
+* Obsolete email syntaxes are rejected:
+ The unusual ["(comment)" syntax](https://github.com/JoshData/python-email-validator/issues/77)
+ is rejected. Extremely old obsolete syntaxes are
+ rejected. Quoted-string local parts and domain-literal addresses
+ are rejected by default, but there are options to allow them (see above).
+ No one uses these forms anymore, and I can't think of any reason why anyone
+ using this library would need to accept them.
+
+Testing
+-------
+
+Tests can be run using
+
+```sh
+pip install -r test_requirements.txt
+make test
+```
+
+Tests run with mocked DNS responses. When adding or changing tests, temporarily turn on the `BUILD_MOCKED_DNS_RESPONSE_DATA` flag in `tests/mocked_dns_responses.py` to re-build the database of mocked responses from live queries.
+
+For Project Maintainers
+-----------------------
+
+The package is distributed as a universal wheel and as a source package.
+
+To release:
+
+* Update CHANGELOG.md.
+* Update the version number in `email_validator/version.py`.
+* Make & push a commit with the new version number and make sure tests pass.
+* Make & push a tag (see command below).
+* Make a release at https://github.com/JoshData/python-email-validator/releases/new.
+* Publish a source and wheel distribution to pypi (see command below).
+
+```sh
+git tag v$(cat email_validator/version.py | sed "s/.* = //" | sed 's/"//g')
+git push --tags
+./release_to_pypi.sh
+```
+
+License
+-------
+
+This project is free of any copyright restrictions per the [Unlicense](https://unlicense.org/). (Prior to Feb. 4, 2024, the project was made available under the terms of the [CC0 1.0 Universal public domain dedication](http://creativecommons.org/publicdomain/zero/1.0/).) See [LICENSE](LICENSE) and [CONTRIBUTING.md](CONTRIBUTING.md).
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..919e7176105a8010ca0aa44fca431303084b4443
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/RECORD
@@ -0,0 +1,25 @@
+../../Scripts/email_validator.exe,sha256=Mvg4Syidk_ExfGnQyqTJhHhZZovAY7dmveyd1kqJEJk,108469
+email_validator-2.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+email_validator-2.1.1.dist-info/LICENSE,sha256=ZyF5dS4QkTSj-yvdB4Cyn9t6A5dPD1hqE66tUSlWLUw,1212
+email_validator-2.1.1.dist-info/METADATA,sha256=MdQTRFU1P-8zJanuHmDRDF5TaOktjmoUNLus2yjrfjs,26149
+email_validator-2.1.1.dist-info/RECORD,,
+email_validator-2.1.1.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
+email_validator-2.1.1.dist-info/entry_points.txt,sha256=zRM_6bNIUSHTbNx5u6M3nK1MAguvryrc9hICC6HyrBg,66
+email_validator-2.1.1.dist-info/top_level.txt,sha256=fYDOSWFZke46ut7WqdOAJjjhlpPYAaOwOwIsh3s8oWI,16
+email_validator/__init__.py,sha256=PoZLrr5AblW0FfPlT-EBKwOmM07xHw7ZtfHECZLz75Q,4211
+email_validator/__main__.py,sha256=SgarDcfH3W5KlcuUi6aaiQPqMdL3C-mOZVnTS6WesS4,2146
+email_validator/__pycache__/__init__.cpython-311.pyc,,
+email_validator/__pycache__/__main__.cpython-311.pyc,,
+email_validator/__pycache__/deliverability.cpython-311.pyc,,
+email_validator/__pycache__/exceptions_types.cpython-311.pyc,,
+email_validator/__pycache__/rfc_constants.cpython-311.pyc,,
+email_validator/__pycache__/syntax.cpython-311.pyc,,
+email_validator/__pycache__/validate_email.cpython-311.pyc,,
+email_validator/__pycache__/version.cpython-311.pyc,,
+email_validator/deliverability.py,sha256=573d02Sx_YdlwPNW6yMRGQm5tUv3ffHUUGsShcs4mAY,5927
+email_validator/exceptions_types.py,sha256=wnHFGKAfiSiaJlsOA-WgKN-MyGE9AlTJit8oEZZW8Tw,5718
+email_validator/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+email_validator/rfc_constants.py,sha256=lpfWHURNe8ZhxJ3VojfllTaZ8_y_VDPgMhrG3khoSA4,2721
+email_validator/syntax.py,sha256=zYWYGkSODYwFApqIg-Jfqgm4XIg0Cd-tGrrvCc-bIC4,27617
+email_validator/validate_email.py,sha256=GKI23zCdz30R1PY30u34zsPZCAX-T055-Lj5dygitlE,6597
+email_validator/version.py,sha256=zPJIgPGcoSNiD0qme18OnYJYE3A9VVytlhO-V5DaAW0,22
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..98c0d20b7a64f4f998d7913e1d38a05dba20916c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.42.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/entry_points.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..03c6e23010b8a919ee98bbb007cbb06b99c3160b
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[console_scripts]
+email_validator = email_validator.__main__:main
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/top_level.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..798fd5ef9f745d52de66401eacd4fd74cbf3dbbb
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator-2.1.1.dist-info/top_level.txt
@@ -0,0 +1 @@
+email_validator
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd1b301755a775084fd5b7e092e21830460f7b45
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/__init__.py
@@ -0,0 +1,96 @@
+# Export the main method, helper methods, and the public data types.
+from .exceptions_types import ValidatedEmail, EmailNotValidError, \
+ EmailSyntaxError, EmailUndeliverableError
+from .validate_email import validate_email
+from .version import __version__
+
+__all__ = ["validate_email",
+ "ValidatedEmail", "EmailNotValidError",
+ "EmailSyntaxError", "EmailUndeliverableError",
+ "caching_resolver", "__version__"]
+
+
+def caching_resolver(*args, **kwargs):
+ # Lazy load `deliverability` as it is slow to import (due to dns.resolver)
+ from .deliverability import caching_resolver
+
+ return caching_resolver(*args, **kwargs)
+
+
+# These global attributes are a part of the library's API and can be
+# changed by library users.
+
+# Default values for keyword arguments.
+
+ALLOW_SMTPUTF8 = True
+ALLOW_QUOTED_LOCAL = False
+ALLOW_DOMAIN_LITERAL = False
+GLOBALLY_DELIVERABLE = True
+CHECK_DELIVERABILITY = True
+TEST_ENVIRONMENT = False
+DEFAULT_TIMEOUT = 15 # secs
+
+# IANA Special Use Domain Names
+# Last Updated 2021-09-21
+# https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.txt
+#
+# The domain names without dots would be caught by the check that the domain
+# name in an email address must have a period, but this list will also catch
+# subdomains of these domains, which are also reserved.
+SPECIAL_USE_DOMAIN_NAMES = [
+ # The "arpa" entry here is consolidated from a lot of arpa subdomains
+ # for private address (i.e. non-routable IP addresses like 172.16.x.x)
+ # reverse mapping, plus some other subdomains. Although RFC 6761 says
+ # that application software should not treat these domains as special,
+ # they are private-use domains and so cannot have globally deliverable
+ # email addresses, which is an assumption of this library, and probably
+ # all of arpa is similarly special-use, so we reject it all.
+ "arpa",
+
+ # RFC 6761 says applications "SHOULD NOT" treat the "example" domains
+ # as special, i.e. applications should accept these domains.
+ #
+ # The domain "example" alone fails our syntax validation because it
+ # lacks a dot (we assume no one has an email address on a TLD directly).
+ # "@example.com/net/org" will currently fail DNS-based deliverability
+ # checks because IANA publishes a NULL MX for these domains, and
+ # "@mail.example[.com/net/org]" and other subdomains will fail DNS-
+ # based deliverability checks because IANA does not publish MX or A
+ # DNS records for these subdomains.
+ # "example", # i.e. "wwww.example"
+ # "example.com",
+ # "example.net",
+ # "example.org",
+
+ # RFC 6761 says that applications are permitted to treat this domain
+ # as special and that DNS should return an immediate negative response,
+ # so we also immediately reject this domain, which also follows the
+ # purpose of the domain.
+ "invalid",
+
+ # RFC 6762 says that applications "may" treat ".local" as special and
+ # that "name resolution APIs and libraries SHOULD recognize these names
+ # as special," and since ".local" has no global definition, we reject
+ # it, as we expect email addresses to be gloally routable.
+ "local",
+
+ # RFC 6761 says that applications (like this library) are permitted
+ # to treat "localhost" as special, and since it cannot have a globally
+ # deliverable email address, we reject it.
+ "localhost",
+
+ # RFC 7686 says "applications that do not implement the Tor protocol
+ # SHOULD generate an error upon the use of .onion and SHOULD NOT
+ # perform a DNS lookup.
+ "onion",
+
+ # Although RFC 6761 says that application software should not treat
+ # these domains as special, it also warns users that the address may
+ # resolve differently in different systems, and therefore it cannot
+ # have a globally routable email address, which is an assumption of
+ # this library, so we reject "@test" and "@*.test" addresses, unless
+ # the test_environment keyword argument is given, to allow their use
+ # in application-level test environments. These domains will generally
+ # fail deliverability checks because "test" is not an actual TLD.
+ "test",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/__main__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a414ff6fcaee7be32c3aef63de08d2d87de55920
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/__main__.py
@@ -0,0 +1,59 @@
+# A command-line tool for testing.
+#
+# Usage:
+#
+# python -m email_validator test@example.org
+# python -m email_validator < LIST_OF_ADDRESSES.TXT
+#
+# Provide email addresses to validate either as a command-line argument
+# or in STDIN separated by newlines. Validation errors will be printed for
+# invalid email addresses. When passing an email address on the command
+# line, if the email address is valid, information about it will be printed.
+# When using STDIN, no output will be given for valid email addresses.
+#
+# Keyword arguments to validate_email can be set in environment variables
+# of the same name but upprcase (see below).
+
+import json
+import os
+import sys
+
+from .validate_email import validate_email
+from .deliverability import caching_resolver
+from .exceptions_types import EmailNotValidError
+
+
+def main(dns_resolver=None):
+ # The dns_resolver argument is for tests.
+
+ # Set options from environment variables.
+ options = {}
+ for varname in ('ALLOW_SMTPUTF8', 'ALLOW_QUOTED_LOCAL', 'ALLOW_DOMAIN_LITERAL',
+ 'GLOBALLY_DELIVERABLE', 'CHECK_DELIVERABILITY', 'TEST_ENVIRONMENT'):
+ if varname in os.environ:
+ options[varname.lower()] = bool(os.environ[varname])
+ for varname in ('DEFAULT_TIMEOUT',):
+ if varname in os.environ:
+ options[varname.lower()] = float(os.environ[varname])
+
+ if len(sys.argv) == 1:
+ # Validate the email addresses pased line-by-line on STDIN.
+ dns_resolver = dns_resolver or caching_resolver()
+ for line in sys.stdin:
+ email = line.strip()
+ try:
+ validate_email(email, dns_resolver=dns_resolver, **options)
+ except EmailNotValidError as e:
+ print(f"{email} {e}")
+ else:
+ # Validate the email address passed on the command line.
+ email = sys.argv[1]
+ try:
+ result = validate_email(email, dns_resolver=dns_resolver, **options)
+ print(json.dumps(result.as_dict(), indent=2, sort_keys=True, ensure_ascii=False))
+ except EmailNotValidError as e:
+ print(e)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/deliverability.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/deliverability.py
new file mode 100644
index 0000000000000000000000000000000000000000..182331ad600054080b23e13b22a755aaae9608ff
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/deliverability.py
@@ -0,0 +1,127 @@
+from typing import Optional, Any, Dict
+
+from .exceptions_types import EmailUndeliverableError
+
+import dns.resolver
+import dns.exception
+
+
+def caching_resolver(*, timeout: Optional[int] = None, cache=None, dns_resolver=None):
+ if timeout is None:
+ from . import DEFAULT_TIMEOUT
+ timeout = DEFAULT_TIMEOUT
+ resolver = dns_resolver or dns.resolver.Resolver()
+ resolver.cache = cache or dns.resolver.LRUCache() # type: ignore
+ resolver.lifetime = timeout # type: ignore # timeout, in seconds
+ return resolver
+
+
+def validate_email_deliverability(domain: str, domain_i18n: str, timeout: Optional[int] = None, dns_resolver=None):
+ # Check that the domain resolves to an MX record. If there is no MX record,
+ # try an A or AAAA record which is a deprecated fallback for deliverability.
+ # Raises an EmailUndeliverableError on failure. On success, returns a dict
+ # with deliverability information.
+
+ # If no dns.resolver.Resolver was given, get dnspython's default resolver.
+ # Override the default resolver's timeout. This may affect other uses of
+ # dnspython in this process.
+ if dns_resolver is None:
+ from . import DEFAULT_TIMEOUT
+ if timeout is None:
+ timeout = DEFAULT_TIMEOUT
+ dns_resolver = dns.resolver.get_default_resolver()
+ dns_resolver.lifetime = timeout
+ elif timeout is not None:
+ raise ValueError("It's not valid to pass both timeout and dns_resolver.")
+
+ deliverability_info: Dict[str, Any] = {}
+
+ try:
+ try:
+ # Try resolving for MX records (RFC 5321 Section 5).
+ response = dns_resolver.resolve(domain, "MX")
+
+ # For reporting, put them in priority order and remove the trailing dot in the qnames.
+ mtas = sorted([(r.preference, str(r.exchange).rstrip('.')) for r in response])
+
+ # RFC 7505: Null MX (0, ".") records signify the domain does not accept email.
+ # Remove null MX records from the mtas list (but we've stripped trailing dots,
+ # so the 'exchange' is just "") so we can check if there are no non-null MX
+ # records remaining.
+ mtas = [(preference, exchange) for preference, exchange in mtas
+ if exchange != ""]
+ if len(mtas) == 0: # null MX only, if there were no MX records originally a NoAnswer exception would have occurred
+ raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.")
+
+ deliverability_info["mx"] = mtas
+ deliverability_info["mx_fallback_type"] = None
+
+ except dns.resolver.NoAnswer:
+ # If there was no MX record, fall back to an A record. (RFC 5321 Section 5)
+ try:
+ response = dns_resolver.resolve(domain, "A")
+ deliverability_info["mx"] = [(0, str(r)) for r in response]
+ deliverability_info["mx_fallback_type"] = "A"
+
+ except dns.resolver.NoAnswer:
+
+ # If there was no A record, fall back to an AAAA record.
+ # (It's unclear if SMTP servers actually do this.)
+ try:
+ response = dns_resolver.resolve(domain, "AAAA")
+ deliverability_info["mx"] = [(0, str(r)) for r in response]
+ deliverability_info["mx_fallback_type"] = "AAAA"
+
+ except dns.resolver.NoAnswer as e:
+ # If there was no MX, A, or AAAA record, then mail to
+ # this domain is not deliverable, although the domain
+ # name has other records (otherwise NXDOMAIN would
+ # have been raised).
+ raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.") from e
+
+ # Check for a SPF (RFC 7208) reject-all record ("v=spf1 -all") which indicates
+ # no emails are sent from this domain (similar to a Null MX record
+ # but for sending rather than receiving). In combination with the
+ # absence of an MX record, this is probably a good sign that the
+ # domain is not used for email.
+ try:
+ response = dns_resolver.resolve(domain, "TXT")
+ for rec in response:
+ value = b"".join(rec.strings)
+ if value.startswith(b"v=spf1 "):
+ deliverability_info["spf"] = value.decode("ascii", errors='replace')
+ if value == b"v=spf1 -all":
+ raise EmailUndeliverableError(f"The domain name {domain_i18n} does not send email.")
+ except dns.resolver.NoAnswer:
+ # No TXT records means there is no SPF policy, so we cannot take any action.
+ pass
+
+ except dns.resolver.NXDOMAIN as e:
+ # The domain name does not exist --- there are no records of any sort
+ # for the domain name.
+ raise EmailUndeliverableError(f"The domain name {domain_i18n} does not exist.") from e
+
+ except dns.resolver.NoNameservers:
+ # All nameservers failed to answer the query. This might be a problem
+ # with local nameservers, maybe? We'll allow the domain to go through.
+ return {
+ "unknown-deliverability": "no_nameservers",
+ }
+
+ except dns.exception.Timeout:
+ # A timeout could occur for various reasons, so don't treat it as a failure.
+ return {
+ "unknown-deliverability": "timeout",
+ }
+
+ except EmailUndeliverableError:
+ # Don't let these get clobbered by the wider except block below.
+ raise
+
+ except Exception as e:
+ # Unhandled conditions should not propagate.
+ raise EmailUndeliverableError(
+ "There was an error while checking if the domain name in the email address is deliverable: " + str(e)
+ ) from e
+
+ return deliverability_info
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/exceptions_types.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/exceptions_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..4522b4f64a22c966fea2d336044d09b196d654eb
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/exceptions_types.py
@@ -0,0 +1,141 @@
+import warnings
+from typing import Optional
+
+
+class EmailNotValidError(ValueError):
+ """Parent class of all exceptions raised by this module."""
+ pass
+
+
+class EmailSyntaxError(EmailNotValidError):
+ """Exception raised when an email address fails validation because of its form."""
+ pass
+
+
+class EmailUndeliverableError(EmailNotValidError):
+ """Exception raised when an email address fails validation because its domain name does not appear deliverable."""
+ pass
+
+
+class ValidatedEmail:
+ """The validate_email function returns objects of this type holding the normalized form of the email address
+ and other information."""
+
+ """The email address that was passed to validate_email. (If passed as bytes, this will be a string.)"""
+ original: str
+
+ """The normalized email address, which should always be used in preferance to the original address.
+ The normalized address converts an IDNA ASCII domain name to Unicode, if possible, and performs
+ Unicode normalization on the local part and on the domain (if originally Unicode). It is the
+ concatenation of the local_part and domain attributes, separated by an @-sign."""
+ normalized: str
+
+ """The local part of the email address after Unicode normalization."""
+ local_part: str
+
+ """The domain part of the email address after Unicode normalization or conversion to
+ Unicode from IDNA ascii."""
+ domain: str
+
+ """If the domain part is a domain literal, the IPv4Address or IPv6Address object."""
+ domain_address: object
+
+ """If not None, a form of the email address that uses 7-bit ASCII characters only."""
+ ascii_email: Optional[str]
+
+ """If not None, the local part of the email address using 7-bit ASCII characters only."""
+ ascii_local_part: Optional[str]
+
+ """A form of the domain name that uses 7-bit ASCII characters only."""
+ ascii_domain: str
+
+ """If True, the SMTPUTF8 feature of your mail relay will be required to transmit messages
+ to this address. This flag is True just when ascii_local_part is missing. Otherwise it
+ is False."""
+ smtputf8: bool
+
+ """If a deliverability check is performed and if it succeeds, a list of (priority, domain)
+ tuples of MX records specified in the DNS for the domain."""
+ mx: list
+
+ """If no MX records are actually specified in DNS and instead are inferred, through an obsolete
+ mechanism, from A or AAAA records, the value is the type of DNS record used instead (`A` or `AAAA`)."""
+ mx_fallback_type: str
+
+ """Tests use this constructor."""
+ def __init__(self, **kwargs):
+ for k, v in kwargs.items():
+ setattr(self, k, v)
+
+ def __repr__(self):
+ return f""
+
+ """For backwards compatibility, support old field names."""
+ def __getattr__(self, key):
+ if key == "original_email":
+ return self.original
+ if key == "email":
+ return self.normalized
+ raise AttributeError(key)
+
+ @property
+ def email(self):
+ warnings.warn("ValidatedEmail.email is deprecated and will be removed, use ValidatedEmail.normalized instead", DeprecationWarning)
+ return self.normalized
+
+ """For backwards compatibility, some fields are also exposed through a dict-like interface. Note
+ that some of the names changed when they became attributes."""
+ def __getitem__(self, key):
+ warnings.warn("dict-like access to the return value of validate_email is deprecated and may not be supported in the future.", DeprecationWarning, stacklevel=2)
+ if key == "email":
+ return self.normalized
+ if key == "email_ascii":
+ return self.ascii_email
+ if key == "local":
+ return self.local_part
+ if key == "domain":
+ return self.ascii_domain
+ if key == "domain_i18n":
+ return self.domain
+ if key == "smtputf8":
+ return self.smtputf8
+ if key == "mx":
+ return self.mx
+ if key == "mx-fallback":
+ return self.mx_fallback_type
+ raise KeyError()
+
+ """Tests use this."""
+ def __eq__(self, other):
+ if not isinstance(other, ValidatedEmail):
+ return False
+ return (
+ self.normalized == other.normalized
+ and self.local_part == other.local_part
+ and self.domain == other.domain
+ and getattr(self, 'ascii_email', None) == getattr(other, 'ascii_email', None)
+ and getattr(self, 'ascii_local_part', None) == getattr(other, 'ascii_local_part', None)
+ and getattr(self, 'ascii_domain', None) == getattr(other, 'ascii_domain', None)
+ and self.smtputf8 == other.smtputf8
+ and repr(sorted(self.mx) if getattr(self, 'mx', None) else None)
+ == repr(sorted(other.mx) if getattr(other, 'mx', None) else None)
+ and getattr(self, 'mx_fallback_type', None) == getattr(other, 'mx_fallback_type', None)
+ )
+
+ """This helps producing the README."""
+ def as_constructor(self):
+ return "ValidatedEmail(" \
+ + ",".join(f"\n {key}={repr(getattr(self, key))}"
+ for key in ('normalized', 'local_part', 'domain',
+ 'ascii_email', 'ascii_local_part', 'ascii_domain',
+ 'smtputf8', 'mx', 'mx_fallback_type')
+ if hasattr(self, key)
+ ) \
+ + ")"
+
+ """Convenience method for accessing ValidatedEmail as a dict"""
+ def as_dict(self):
+ d = self.__dict__
+ if d.get('domain_address'):
+ d['domain_address'] = repr(d['domain_address'])
+ return d
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/py.typed b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/rfc_constants.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/rfc_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6b9c59220ab715d2817cfb6c00754fe15cdffda
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/rfc_constants.py
@@ -0,0 +1,52 @@
+# These constants are defined by the email specifications.
+
+import re
+
+# Based on RFC 5322 3.2.3, these characters are permitted in email
+# addresses (not taking into account internationalization) separated by dots:
+ATEXT = r'a-zA-Z0-9_!#\$%&\'\*\+\-/=\?\^`\{\|\}~'
+ATEXT_RE = re.compile('[.' + ATEXT + ']') # ATEXT plus dots
+DOT_ATOM_TEXT = re.compile('[' + ATEXT + ']+(?:\\.[' + ATEXT + r']+)*\Z')
+
+# RFC 6531 3.3 extends the allowed characters in internationalized
+# addresses to also include three specific ranges of UTF8 defined in
+# RFC 3629 section 4, which appear to be the Unicode code points from
+# U+0080 to U+10FFFF.
+ATEXT_INTL = ATEXT + "\u0080-\U0010FFFF"
+ATEXT_INTL_RE = re.compile('[.' + ATEXT_INTL + ']') # ATEXT_INTL plus dots
+DOT_ATOM_TEXT_INTL = re.compile('[' + ATEXT_INTL + ']+(?:\\.[' + ATEXT_INTL + r']+)*\Z')
+
+# The domain part of the email address, after IDNA (ASCII) encoding,
+# must also satisfy the requirements of RFC 952/RFC 1123 2.1 which
+# restrict the allowed characters of hostnames further.
+ATEXT_HOSTNAME_INTL = re.compile(r"[a-zA-Z0-9\-\." + "\u0080-\U0010FFFF" + "]")
+HOSTNAME_LABEL = r'(?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]*)?[a-zA-Z0-9])'
+DOT_ATOM_TEXT_HOSTNAME = re.compile(HOSTNAME_LABEL + r'(?:\.' + HOSTNAME_LABEL + r')*\Z')
+DOMAIN_NAME_REGEX = re.compile(r"[A-Za-z]\Z") # all TLDs currently end with a letter
+
+# Domain literal (RFC 5322 3.4.1)
+DOMAIN_LITERAL_CHARS = re.compile(r"[\u0021-\u00FA\u005E-\u007E]")
+
+# Quoted-string local part (RFC 5321 4.1.2, internationalized by RFC 6531 3.3)
+# The permitted characters in a quoted string are the characters in the range
+# 32-126, except that quotes and (literal) backslashes can only appear when escaped
+# by a backslash. When internationalized, UTF8 strings are also permitted except
+# the ASCII characters that are not previously permitted (see above).
+# QUOTED_LOCAL_PART_ADDR = re.compile(r"^\"((?:[\u0020-\u0021\u0023-\u005B\u005D-\u007E]|\\[\u0020-\u007E])*)\"@(.*)")
+QUOTED_LOCAL_PART_ADDR = re.compile(r"^\"((?:[^\"\\]|\\.)*)\"@(.*)")
+QTEXT_INTL = re.compile(r"[\u0020-\u007E\u0080-\U0010FFFF]")
+
+# Length constants
+# RFC 3696 + errata 1003 + errata 1690 (https://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690)
+# explains the maximum length of an email address is 254 octets.
+EMAIL_MAX_LENGTH = 254
+LOCAL_PART_MAX_LENGTH = 64
+DNS_LABEL_LENGTH_LIMIT = 63 # in "octets", RFC 1035 2.3.1
+DOMAIN_MAX_LENGTH = 255 # in "octets", RFC 1035 2.3.4 and RFC 5321 4.5.3.1.2
+
+# RFC 2142
+CASE_INSENSITIVE_MAILBOX_NAMES = [
+ 'info', 'marketing', 'sales', 'support', # section 3
+ 'abuse', 'noc', 'security', # section 4
+ 'postmaster', 'hostmaster', 'usenet', 'news', 'webmaster', 'www', 'uucp', 'ftp', # section 5
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/syntax.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/syntax.py
new file mode 100644
index 0000000000000000000000000000000000000000..6634ace24017b668f31927b84c62bfbff31f50f5
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/syntax.py
@@ -0,0 +1,563 @@
+from .exceptions_types import EmailSyntaxError
+from .rfc_constants import EMAIL_MAX_LENGTH, LOCAL_PART_MAX_LENGTH, DOMAIN_MAX_LENGTH, \
+ DOT_ATOM_TEXT, DOT_ATOM_TEXT_INTL, ATEXT_RE, ATEXT_INTL_RE, ATEXT_HOSTNAME_INTL, QTEXT_INTL, \
+ DNS_LABEL_LENGTH_LIMIT, DOT_ATOM_TEXT_HOSTNAME, DOMAIN_NAME_REGEX, DOMAIN_LITERAL_CHARS, \
+ QUOTED_LOCAL_PART_ADDR
+
+import re
+import unicodedata
+import idna # implements IDNA 2008; Python's codec is only IDNA 2003
+import ipaddress
+from typing import Optional
+
+
+def split_email(email):
+ # Return the local part and domain part of the address and
+ # whether the local part was quoted as a three-tuple.
+
+ # Typical email addresses have a single @-sign, but the
+ # awkward "quoted string" local part form (RFC 5321 4.1.2)
+ # allows @-signs (and escaped quotes) to appear in the local
+ # part if the local part is quoted. If the address is quoted,
+ # split it at a non-escaped @-sign and unescape the escaping.
+ if m := QUOTED_LOCAL_PART_ADDR.match(email):
+ local_part, domain_part = m.groups()
+
+ # Since backslash-escaping is no longer needed because
+ # the quotes are removed, remove backslash-escaping
+ # to return in the normalized form.
+ local_part = re.sub(r"\\(.)", "\\1", local_part)
+
+ return local_part, domain_part, True
+
+ else:
+ # Split at the one and only at-sign.
+ parts = email.split('@')
+ if len(parts) != 2:
+ raise EmailSyntaxError("The email address is not valid. It must have exactly one @-sign.")
+ local_part, domain_part = parts
+ return local_part, domain_part, False
+
+
+def get_length_reason(addr, utf8=False, limit=EMAIL_MAX_LENGTH):
+ """Helper function to return an error message related to invalid length."""
+ diff = len(addr) - limit
+ prefix = "at least " if utf8 else ""
+ suffix = "s" if diff > 1 else ""
+ return f"({prefix}{diff} character{suffix} too many)"
+
+
+def safe_character_display(c):
+ # Return safely displayable characters in quotes.
+ if c == '\\':
+ return f"\"{c}\"" # can't use repr because it escapes it
+ if unicodedata.category(c)[0] in ("L", "N", "P", "S"):
+ return repr(c)
+
+ # Construct a hex string in case the unicode name doesn't exist.
+ if ord(c) < 0xFFFF:
+ h = f"U+{ord(c):04x}".upper()
+ else:
+ h = f"U+{ord(c):08x}".upper()
+
+ # Return the character name or, if it has no name, the hex string.
+ return unicodedata.name(c, h)
+
+
+def validate_email_local_part(local: str, allow_smtputf8: bool = True, allow_empty_local: bool = False,
+ quoted_local_part: bool = False):
+ """Validates the syntax of the local part of an email address."""
+
+ if len(local) == 0:
+ if not allow_empty_local:
+ raise EmailSyntaxError("There must be something before the @-sign.")
+
+ # The caller allows an empty local part. Useful for validating certain
+ # Postfix aliases.
+ return {
+ "local_part": local,
+ "ascii_local_part": local,
+ "smtputf8": False,
+ }
+
+ # Check the length of the local part by counting characters.
+ # (RFC 5321 4.5.3.1.1)
+ # We're checking the number of characters here. If the local part
+ # is ASCII-only, then that's the same as bytes (octets). If it's
+ # internationalized, then the UTF-8 encoding may be longer, but
+ # that may not be relevant. We will check the total address length
+ # instead.
+ if len(local) > LOCAL_PART_MAX_LENGTH:
+ reason = get_length_reason(local, limit=LOCAL_PART_MAX_LENGTH)
+ raise EmailSyntaxError(f"The email address is too long before the @-sign {reason}.")
+
+ # Check the local part against the non-internationalized regular expression.
+ # Most email addresses match this regex so it's probably fastest to check this first.
+ # (RFC 5322 3.2.3)
+ # All local parts matching the dot-atom rule are also valid as a quoted string
+ # so if it was originally quoted (quoted_local_part is True) and this regex matches,
+ # it's ok.
+ # (RFC 5321 4.1.2 / RFC 5322 3.2.4).
+ if DOT_ATOM_TEXT.match(local):
+ # It's valid. And since it's just the permitted ASCII characters,
+ # it's normalized and safe. If the local part was originally quoted,
+ # the quoting was unnecessary and it'll be returned as normalized to
+ # non-quoted form.
+
+ # Return the local part and flag that SMTPUTF8 is not needed.
+ return {
+ "local_part": local,
+ "ascii_local_part": local,
+ "smtputf8": False,
+ }
+
+ # The local part failed the basic dot-atom check. Try the extended character set
+ # for internationalized addresses. It's the same pattern but with additional
+ # characters permitted.
+ # RFC 6531 section 3.3.
+ valid: Optional[str] = None
+ requires_smtputf8 = False
+ if DOT_ATOM_TEXT_INTL.match(local):
+ # But international characters in the local part may not be permitted.
+ if not allow_smtputf8:
+ # Check for invalid characters against the non-internationalized
+ # permitted character set.
+ # (RFC 5322 3.2.3)
+ bad_chars = {
+ safe_character_display(c)
+ for c in local
+ if not ATEXT_RE.match(c)
+ }
+ if bad_chars:
+ raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".")
+
+ # Although the check above should always find something, fall back to this just in case.
+ raise EmailSyntaxError("Internationalized characters before the @-sign are not supported.")
+
+ # It's valid.
+ valid = "dot-atom"
+ requires_smtputf8 = True
+
+ # There are no syntactic restrictions on quoted local parts, so if
+ # it was originally quoted, it is probably valid. More characters
+ # are allowed, like @-signs, spaces, and quotes, and there are no
+ # restrictions on the placement of dots, as in dot-atom local parts.
+ elif quoted_local_part:
+ # Check for invalid characters in a quoted string local part.
+ # (RFC 5321 4.1.2. RFC 5322 lists additional permitted *obsolete*
+ # characters which are *not* allowed here. RFC 6531 section 3.3
+ # extends the range to UTF8 strings.)
+ bad_chars = {
+ safe_character_display(c)
+ for c in local
+ if not QTEXT_INTL.match(c)
+ }
+ if bad_chars:
+ raise EmailSyntaxError("The email address contains invalid characters in quotes before the @-sign: " + ", ".join(sorted(bad_chars)) + ".")
+
+ # See if any characters are outside of the ASCII range.
+ bad_chars = {
+ safe_character_display(c)
+ for c in local
+ if not (32 <= ord(c) <= 126)
+ }
+ if bad_chars:
+ requires_smtputf8 = True
+
+ # International characters in the local part may not be permitted.
+ if not allow_smtputf8:
+ raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".")
+
+ # It's valid.
+ valid = "quoted"
+
+ # If the local part matches the internationalized dot-atom form or was quoted,
+ # perform normalization and additional checks for Unicode strings.
+ if valid:
+ # RFC 6532 section 3.1 says that Unicode NFC normalization should be applied,
+ # so we'll return the normalized local part in the return value.
+ local = unicodedata.normalize("NFC", local)
+
+ # Check that the local part is a valid, safe, and sensible Unicode string.
+ # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked
+ # by DOT_ATOM_TEXT_INTL and QTEXT_INTL. Other characters may be permitted by the
+ # email specs, but they may not be valid, safe, or sensible Unicode strings.
+ # See the function for rationale.
+ check_unsafe_chars(local, allow_space=(valid == "quoted"))
+
+ # Try encoding to UTF-8. Failure is possible with some characters like
+ # surrogate code points, but those are checked above. Still, we don't
+ # want to have an unhandled exception later.
+ try:
+ local.encode("utf8")
+ except ValueError as e:
+ raise EmailSyntaxError("The email address contains an invalid character.") from e
+
+ # If this address passes only by the quoted string form, re-quote it
+ # and backslash-escape quotes and backslashes (removing any unnecessary
+ # escapes). Per RFC 5321 4.1.2, "all quoted forms MUST be treated as equivalent,
+ # and the sending system SHOULD transmit the form that uses the minimum quoting possible."
+ if valid == "quoted":
+ local = '"' + re.sub(r'(["\\])', r'\\\1', local) + '"'
+
+ return {
+ "local_part": local,
+ "ascii_local_part": local if not requires_smtputf8 else None,
+ "smtputf8": requires_smtputf8,
+ }
+
+ # It's not a valid local part. Let's find out why.
+ # (Since quoted local parts are all valid or handled above, these checks
+ # don't apply in those cases.)
+
+ # Check for invalid characters.
+ # (RFC 5322 3.2.3, plus RFC 6531 3.3)
+ bad_chars = {
+ safe_character_display(c)
+ for c in local
+ if not ATEXT_INTL_RE.match(c)
+ }
+ if bad_chars:
+ raise EmailSyntaxError("The email address contains invalid characters before the @-sign: " + ", ".join(sorted(bad_chars)) + ".")
+
+ # Check for dot errors imposted by the dot-atom rule.
+ # (RFC 5322 3.2.3)
+ check_dot_atom(local, 'An email address cannot start with a {}.', 'An email address cannot have a {} immediately before the @-sign.', is_hostname=False)
+
+ # All of the reasons should already have been checked, but just in case
+ # we have a fallback message.
+ raise EmailSyntaxError("The email address contains invalid characters before the @-sign.")
+
+
+def check_unsafe_chars(s, allow_space=False):
+ # Check for unsafe characters or characters that would make the string
+ # invalid or non-sensible Unicode.
+ bad_chars = set()
+ for i, c in enumerate(s):
+ category = unicodedata.category(c)
+ if category[0] in ("L", "N", "P", "S"):
+ # Letters, numbers, punctuation, and symbols are permitted.
+ pass
+ elif category[0] == "M":
+ # Combining character in first position would combine with something
+ # outside of the email address if concatenated, so they are not safe.
+ # We also check if this occurs after the @-sign, which would not be
+ # sensible.
+ if i == 0:
+ bad_chars.add(c)
+ elif category == "Zs":
+ # Spaces outside of the ASCII range are not specifically disallowed in
+ # internationalized addresses as far as I can tell, but they violate
+ # the spirit of the non-internationalized specification that email
+ # addresses do not contain ASCII spaces when not quoted. Excluding
+ # ASCII spaces when not quoted is handled directly by the atom regex.
+ #
+ # In quoted-string local parts, spaces are explicitly permitted, and
+ # the ASCII space has category Zs, so we must allow it here, and we'll
+ # allow all Unicode spaces to be consistent.
+ if not allow_space:
+ bad_chars.add(c)
+ elif category[0] == "Z":
+ # The two line and paragraph separator characters (in categories Zl and Zp)
+ # are not specifically disallowed in internationalized addresses
+ # as far as I can tell, but they violate the spirit of the non-internationalized
+ # specification that email addresses do not contain line breaks when not quoted.
+ bad_chars.add(c)
+ elif category[0] == "C":
+ # Control, format, surrogate, private use, and unassigned code points (C)
+ # are all unsafe in various ways. Control and format characters can affect
+ # text rendering if the email address is concatenated with other text.
+ # Bidirectional format characters are unsafe, even if used properly, because
+ # they cause an email address to render as a different email address.
+ # Private use characters do not make sense for publicly deliverable
+ # email addresses.
+ bad_chars.add(c)
+ else:
+ # All categories should be handled above, but in case there is something new
+ # to the Unicode specification in the future, reject all other categories.
+ bad_chars.add(c)
+ if bad_chars:
+ raise EmailSyntaxError("The email address contains unsafe characters: "
+ + ", ".join(safe_character_display(c) for c in sorted(bad_chars)) + ".")
+
+
+def check_dot_atom(label, start_descr, end_descr, is_hostname):
+ # RFC 5322 3.2.3
+ if label.endswith("."):
+ raise EmailSyntaxError(end_descr.format("period"))
+ if label.startswith("."):
+ raise EmailSyntaxError(start_descr.format("period"))
+ if ".." in label:
+ raise EmailSyntaxError("An email address cannot have two periods in a row.")
+
+ if is_hostname:
+ # RFC 952
+ if label.endswith("-"):
+ raise EmailSyntaxError(end_descr.format("hyphen"))
+ if label.startswith("-"):
+ raise EmailSyntaxError(start_descr.format("hyphen"))
+ if ".-" in label or "-." in label:
+ raise EmailSyntaxError("An email address cannot have a period and a hyphen next to each other.")
+
+
+def validate_email_domain_name(domain, test_environment=False, globally_deliverable=True):
+ """Validates the syntax of the domain part of an email address."""
+
+ # Check for invalid characters before normalization.
+ # (RFC 952 plus RFC 6531 section 3.3 for internationalized addresses)
+ bad_chars = {
+ safe_character_display(c)
+ for c in domain
+ if not ATEXT_HOSTNAME_INTL.match(c)
+ }
+ if bad_chars:
+ raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".")
+
+ # Check for unsafe characters.
+ # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked
+ # by DOT_ATOM_TEXT_INTL. Other characters may be permitted by the email specs, but
+ # they may not be valid, safe, or sensible Unicode strings.
+ check_unsafe_chars(domain)
+
+ # Perform UTS-46 normalization, which includes casefolding, NFC normalization,
+ # and converting all label separators (the period/full stop, fullwidth full stop,
+ # ideographic full stop, and halfwidth ideographic full stop) to regular dots.
+ # It will also raise an exception if there is an invalid character in the input,
+ # such as "⒈" which is invalid because it would expand to include a dot.
+ # Since several characters are normalized to a dot, this has to come before
+ # checks related to dots, like check_dot_atom which comes next.
+ try:
+ domain = idna.uts46_remap(domain, std3_rules=False, transitional=False)
+ except idna.IDNAError as e:
+ raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).") from e
+
+ # The domain part is made up dot-separated "labels." Each label must
+ # have at least one character and cannot start or end with dashes, which
+ # means there are some surprising restrictions on periods and dashes.
+ # Check that before we do IDNA encoding because the IDNA library gives
+ # unfriendly errors for these cases, but after UTS-46 normalization because
+ # it can insert periods and hyphens (from fullwidth characters).
+ # (RFC 952, RFC 1123 2.1, RFC 5322 3.2.3)
+ check_dot_atom(domain, 'An email address cannot have a {} immediately after the @-sign.', 'An email address cannot end with a {}.', is_hostname=True)
+
+ # Check for RFC 5890's invalid R-LDH labels, which are labels that start
+ # with two characters other than "xn" and two dashes.
+ for label in domain.split("."):
+ if re.match(r"(?!xn)..--", label, re.I):
+ raise EmailSyntaxError("An email address cannot have two letters followed by two dashes immediately after the @-sign or after a period, except Punycode.")
+
+ if DOT_ATOM_TEXT_HOSTNAME.match(domain):
+ # This is a valid non-internationalized domain.
+ ascii_domain = domain
+ else:
+ # If international characters are present in the domain name, convert
+ # the domain to IDNA ASCII. If internationalized characters are present,
+ # the MTA must either support SMTPUTF8 or the mail client must convert the
+ # domain name to IDNA before submission.
+ #
+ # Unfortunately this step incorrectly 'fixes' domain names with leading
+ # periods by removing them, so we have to check for this above. It also gives
+ # a funky error message ("No input") when there are two periods in a
+ # row, also checked separately above.
+ #
+ # For ASCII-only domains, the transformation does nothing and is safe to
+ # apply. However, to ensure we don't rely on the idna library for basic
+ # syntax checks, we don't use it if it's not needed.
+ #
+ # uts46 is off here because it is handled above.
+ try:
+ ascii_domain = idna.encode(domain, uts46=False).decode("ascii")
+ except idna.IDNAError as e:
+ if "Domain too long" in str(e):
+ # We can't really be more specific because UTS-46 normalization means
+ # the length check is applied to a string that is different from the
+ # one the user supplied. Also I'm not sure if the length check applies
+ # to the internationalized form, the IDNA ASCII form, or even both!
+ raise EmailSyntaxError("The email address is too long after the @-sign.") from e
+
+ # Other errors seem to not be possible because the call to idna.uts46_remap
+ # would have already raised them.
+ raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).") from e
+
+ # Check the syntax of the string returned by idna.encode.
+ # It should never fail.
+ if not DOT_ATOM_TEXT_HOSTNAME.match(ascii_domain):
+ raise EmailSyntaxError("The email address contains invalid characters after the @-sign after IDNA encoding.")
+
+ # Check the length of the domain name in bytes.
+ # (RFC 1035 2.3.4 and RFC 5321 4.5.3.1.2)
+ # We're checking the number of bytes ("octets") here, which can be much
+ # higher than the number of characters in internationalized domains,
+ # on the assumption that the domain may be transmitted without SMTPUTF8
+ # as IDNA ASCII. (This is also checked by idna.encode, so this exception
+ # is never reached for internationalized domains.)
+ if len(ascii_domain) > DOMAIN_MAX_LENGTH:
+ reason = get_length_reason(ascii_domain, limit=DOMAIN_MAX_LENGTH)
+ raise EmailSyntaxError(f"The email address is too long after the @-sign {reason}.")
+
+ # Also check the label length limit.
+ # (RFC 1035 2.3.1)
+ for label in ascii_domain.split("."):
+ if len(label) > DNS_LABEL_LENGTH_LIMIT:
+ reason = get_length_reason(label, limit=DNS_LABEL_LENGTH_LIMIT)
+ raise EmailSyntaxError(f"After the @-sign, periods cannot be separated by so many characters {reason}.")
+
+ if globally_deliverable:
+ # All publicly deliverable addresses have domain names with at least
+ # one period, at least for gTLDs created since 2013 (per the ICANN Board
+ # New gTLD Program Committee, https://www.icann.org/en/announcements/details/new-gtld-dotless-domain-names-prohibited-30-8-2013-en).
+ # We'll consider the lack of a period a syntax error
+ # since that will match people's sense of what an email address looks
+ # like. We'll skip this in test environments to allow '@test' email
+ # addresses.
+ if "." not in ascii_domain and not (ascii_domain == "test" and test_environment):
+ raise EmailSyntaxError("The part after the @-sign is not valid. It should have a period.")
+
+ # We also know that all TLDs currently end with a letter.
+ if not DOMAIN_NAME_REGEX.search(ascii_domain):
+ raise EmailSyntaxError("The part after the @-sign is not valid. It is not within a valid top-level domain.")
+
+ # Check special-use and reserved domain names.
+ # Some might fail DNS-based deliverability checks, but that
+ # can be turned off, so we should fail them all sooner.
+ # See the references in __init__.py.
+ from . import SPECIAL_USE_DOMAIN_NAMES
+ for d in SPECIAL_USE_DOMAIN_NAMES:
+ # See the note near the definition of SPECIAL_USE_DOMAIN_NAMES.
+ if d == "test" and test_environment:
+ continue
+
+ if ascii_domain == d or ascii_domain.endswith("." + d):
+ raise EmailSyntaxError("The part after the @-sign is a special-use or reserved name that cannot be used with email.")
+
+ # We may have been given an IDNA ASCII domain to begin with. Check
+ # that the domain actually conforms to IDNA. It could look like IDNA
+ # but not be actual IDNA. For ASCII-only domains, the conversion out
+ # of IDNA just gives the same thing back.
+ #
+ # This gives us the canonical internationalized form of the domain.
+ try:
+ domain_i18n = idna.decode(ascii_domain.encode('ascii'))
+ except idna.IDNAError as e:
+ raise EmailSyntaxError(f"The part after the @-sign is not valid IDNA ({e}).") from e
+
+ # Check for invalid characters after normalization. These
+ # should never arise. See the similar checks above.
+ bad_chars = {
+ safe_character_display(c)
+ for c in domain
+ if not ATEXT_HOSTNAME_INTL.match(c)
+ }
+ if bad_chars:
+ raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".")
+ check_unsafe_chars(domain)
+
+ # Return the IDNA ASCII-encoded form of the domain, which is how it
+ # would be transmitted on the wire (except when used with SMTPUTF8
+ # possibly), as well as the canonical Unicode form of the domain,
+ # which is better for display purposes. This should also take care
+ # of RFC 6532 section 3.1's suggestion to apply Unicode NFC
+ # normalization to addresses.
+ return {
+ "ascii_domain": ascii_domain,
+ "domain": domain_i18n,
+ }
+
+
+def validate_email_length(addrinfo):
+ # If the email address has an ASCII representation, then we assume it may be
+ # transmitted in ASCII (we can't assume SMTPUTF8 will be used on all hops to
+ # the destination) and the length limit applies to ASCII characters (which is
+ # the same as octets). The number of characters in the internationalized form
+ # may be many fewer (because IDNA ASCII is verbose) and could be less than 254
+ # Unicode characters, and of course the number of octets over the limit may
+ # not be the number of characters over the limit, so if the email address is
+ # internationalized, we can't give any simple information about why the address
+ # is too long.
+ if addrinfo.ascii_email and len(addrinfo.ascii_email) > EMAIL_MAX_LENGTH:
+ if addrinfo.ascii_email == addrinfo.normalized:
+ reason = get_length_reason(addrinfo.ascii_email)
+ elif len(addrinfo.normalized) > EMAIL_MAX_LENGTH:
+ # If there are more than 254 characters, then the ASCII
+ # form is definitely going to be too long.
+ reason = get_length_reason(addrinfo.normalized, utf8=True)
+ else:
+ reason = "(when converted to IDNA ASCII)"
+ raise EmailSyntaxError(f"The email address is too long {reason}.")
+
+ # In addition, check that the UTF-8 encoding (i.e. not IDNA ASCII and not
+ # Unicode characters) is at most 254 octets. If the addres is transmitted using
+ # SMTPUTF8, then the length limit probably applies to the UTF-8 encoded octets.
+ # If the email address has an ASCII form that differs from its internationalized
+ # form, I don't think the internationalized form can be longer, and so the ASCII
+ # form length check would be sufficient. If there is no ASCII form, then we have
+ # to check the UTF-8 encoding. The UTF-8 encoding could be up to about four times
+ # longer than the number of characters.
+ #
+ # See the length checks on the local part and the domain.
+ if len(addrinfo.normalized.encode("utf8")) > EMAIL_MAX_LENGTH:
+ if len(addrinfo.normalized) > EMAIL_MAX_LENGTH:
+ # If there are more than 254 characters, then the UTF-8
+ # encoding is definitely going to be too long.
+ reason = get_length_reason(addrinfo.normalized, utf8=True)
+ else:
+ reason = "(when encoded in bytes)"
+ raise EmailSyntaxError(f"The email address is too long {reason}.")
+
+
+def validate_email_domain_literal(domain_literal):
+ # This is obscure domain-literal syntax. Parse it and return
+ # a compressed/normalized address.
+ # RFC 5321 4.1.3 and RFC 5322 3.4.1.
+
+ # Try to parse the domain literal as an IPv4 address.
+ # There is no tag for IPv4 addresses, so we can never
+ # be sure if the user intends an IPv4 address.
+ if re.match(r"^[0-9\.]+$", domain_literal):
+ try:
+ addr = ipaddress.IPv4Address(domain_literal)
+ except ValueError as e:
+ raise EmailSyntaxError(f"The address in brackets after the @-sign is not valid: It is not an IPv4 address ({e}) or is missing an address literal tag.") from e
+
+ # Return the IPv4Address object and the domain back unchanged.
+ return {
+ "domain_address": addr,
+ "domain": f"[{addr}]",
+ }
+
+ # If it begins with "IPv6:" it's an IPv6 address.
+ if domain_literal.startswith("IPv6:"):
+ try:
+ addr = ipaddress.IPv6Address(domain_literal[5:])
+ except ValueError as e:
+ raise EmailSyntaxError(f"The IPv6 address in brackets after the @-sign is not valid ({e}).") from e
+
+ # Return the IPv6Address object and construct a normalized
+ # domain literal.
+ return {
+ "domain_address": addr,
+ "domain": f"[IPv6:{addr.compressed}]",
+ }
+
+ # Nothing else is valid.
+
+ if ":" not in domain_literal:
+ raise EmailSyntaxError("The part after the @-sign in brackets is not an IPv4 address and has no address literal tag.")
+
+ # The tag (the part before the colon) has character restrictions,
+ # but since it must come from a registry of tags (in which only "IPv6" is defined),
+ # there's no need to check the syntax of the tag. See RFC 5321 4.1.2.
+
+ # Check for permitted ASCII characters. This actually doesn't matter
+ # since there will be an exception after anyway.
+ bad_chars = {
+ safe_character_display(c)
+ for c in domain_literal
+ if not DOMAIN_LITERAL_CHARS.match(c)
+ }
+ if bad_chars:
+ raise EmailSyntaxError("The part after the @-sign contains invalid characters in brackets: " + ", ".join(sorted(bad_chars)) + ".")
+
+ # There are no other domain literal tags.
+ # https://www.iana.org/assignments/address-literal-tags/address-literal-tags.xhtml
+ raise EmailSyntaxError("The part after the @-sign contains an invalid address literal tag in brackets.")
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/validate_email.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/validate_email.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6051a943ef32cf3250d8049e06d6dcc76745e3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/validate_email.py
@@ -0,0 +1,146 @@
+from typing import Optional, Union
+
+from .exceptions_types import EmailSyntaxError, ValidatedEmail
+from .syntax import split_email, validate_email_local_part, validate_email_domain_name, validate_email_domain_literal, validate_email_length
+from .rfc_constants import CASE_INSENSITIVE_MAILBOX_NAMES
+
+
+def validate_email(
+ email: Union[str, bytes],
+ /, # prior arguments are positional-only
+ *, # subsequent arguments are keyword-only
+ allow_smtputf8: Optional[bool] = None,
+ allow_empty_local: bool = False,
+ allow_quoted_local: Optional[bool] = None,
+ allow_domain_literal: Optional[bool] = None,
+ check_deliverability: Optional[bool] = None,
+ test_environment: Optional[bool] = None,
+ globally_deliverable: Optional[bool] = None,
+ timeout: Optional[int] = None,
+ dns_resolver: Optional[object] = None
+) -> ValidatedEmail:
+ """
+ Given an email address, and some options, returns a ValidatedEmail instance
+ with information about the address if it is valid or, if the address is not
+ valid, raises an EmailNotValidError. This is the main function of the module.
+ """
+
+ # Fill in default values of arguments.
+ from . import ALLOW_SMTPUTF8, ALLOW_QUOTED_LOCAL, ALLOW_DOMAIN_LITERAL, \
+ GLOBALLY_DELIVERABLE, CHECK_DELIVERABILITY, TEST_ENVIRONMENT, DEFAULT_TIMEOUT
+ if allow_smtputf8 is None:
+ allow_smtputf8 = ALLOW_SMTPUTF8
+ if allow_quoted_local is None:
+ allow_quoted_local = ALLOW_QUOTED_LOCAL
+ if allow_domain_literal is None:
+ allow_domain_literal = ALLOW_DOMAIN_LITERAL
+ if check_deliverability is None:
+ check_deliverability = CHECK_DELIVERABILITY
+ if test_environment is None:
+ test_environment = TEST_ENVIRONMENT
+ if globally_deliverable is None:
+ globally_deliverable = GLOBALLY_DELIVERABLE
+ if timeout is None and dns_resolver is None:
+ timeout = DEFAULT_TIMEOUT
+
+ # Allow email to be a str or bytes instance. If bytes,
+ # it must be ASCII because that's how the bytes work
+ # on the wire with SMTP.
+ if not isinstance(email, str):
+ try:
+ email = email.decode("ascii")
+ except ValueError as e:
+ raise EmailSyntaxError("The email address is not valid ASCII.") from e
+
+ # Split the address into the local part (before the @-sign)
+ # and the domain part (after the @-sign). Normally, there
+ # is only one @-sign. But the awkward "quoted string" local
+ # part form (RFC 5321 4.1.2) allows @-signs in the local
+ # part if the local part is quoted.
+ local_part, domain_part, is_quoted_local_part \
+ = split_email(email)
+
+ # Collect return values in this instance.
+ ret = ValidatedEmail()
+ ret.original = email
+
+ # Validate the email address's local part syntax and get a normalized form.
+ # If the original address was quoted and the decoded local part is a valid
+ # unquoted local part, then we'll get back a normalized (unescaped) local
+ # part.
+ local_part_info = validate_email_local_part(local_part,
+ allow_smtputf8=allow_smtputf8,
+ allow_empty_local=allow_empty_local,
+ quoted_local_part=is_quoted_local_part)
+ ret.local_part = local_part_info["local_part"]
+ ret.ascii_local_part = local_part_info["ascii_local_part"]
+ ret.smtputf8 = local_part_info["smtputf8"]
+
+ # If a quoted local part isn't allowed but is present, now raise an exception.
+ # This is done after any exceptions raised by validate_email_local_part so
+ # that mandatory checks have highest precedence.
+ if is_quoted_local_part and not allow_quoted_local:
+ raise EmailSyntaxError("Quoting the part before the @-sign is not allowed here.")
+
+ # Some local parts are required to be case-insensitive, so we should normalize
+ # to lowercase.
+ # RFC 2142
+ if ret.ascii_local_part is not None \
+ and ret.ascii_local_part.lower() in CASE_INSENSITIVE_MAILBOX_NAMES \
+ and ret.local_part is not None:
+ ret.ascii_local_part = ret.ascii_local_part.lower()
+ ret.local_part = ret.local_part.lower()
+
+ # Validate the email address's domain part syntax and get a normalized form.
+ is_domain_literal = False
+ if len(domain_part) == 0:
+ raise EmailSyntaxError("There must be something after the @-sign.")
+
+ elif domain_part.startswith("[") and domain_part.endswith("]"):
+ # Parse the address in the domain literal and get back a normalized domain.
+ domain_part_info = validate_email_domain_literal(domain_part[1:-1])
+ if not allow_domain_literal:
+ raise EmailSyntaxError("A bracketed IP address after the @-sign is not allowed here.")
+ ret.domain = domain_part_info["domain"]
+ ret.ascii_domain = domain_part_info["domain"] # Domain literals are always ASCII.
+ ret.domain_address = domain_part_info["domain_address"]
+ is_domain_literal = True # Prevent deliverability checks.
+
+ else:
+ # Check the syntax of the domain and get back a normalized
+ # internationalized and ASCII form.
+ domain_part_info = validate_email_domain_name(domain_part, test_environment=test_environment, globally_deliverable=globally_deliverable)
+ ret.domain = domain_part_info["domain"]
+ ret.ascii_domain = domain_part_info["ascii_domain"]
+
+ # Construct the complete normalized form.
+ ret.normalized = ret.local_part + "@" + ret.domain
+
+ # If the email address has an ASCII form, add it.
+ if not ret.smtputf8:
+ if not ret.ascii_domain:
+ raise Exception("Missing ASCII domain.")
+ ret.ascii_email = (ret.ascii_local_part or "") + "@" + ret.ascii_domain
+ else:
+ ret.ascii_email = None
+
+ # Check the length of the address.
+ validate_email_length(ret)
+
+ if check_deliverability and not test_environment:
+ # Validate the email address's deliverability using DNS
+ # and update the returned ValidatedEmail object with metadata.
+
+ if is_domain_literal:
+ # There is nothing to check --- skip deliverability checks.
+ return ret
+
+ # Lazy load `deliverability` as it is slow to import (due to dns.resolver)
+ from .deliverability import validate_email_deliverability
+ deliverability_info = validate_email_deliverability(
+ ret.ascii_domain, ret.domain, timeout, dns_resolver
+ )
+ for key, value in deliverability_info.items():
+ setattr(ret, key, value)
+
+ return ret
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..58039f50515cbb160b60f797ba69002ba1f18f43
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/email_validator/version.py
@@ -0,0 +1 @@
+__version__ = "2.1.1"
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4919efd8f6a8877745eb3e21528d4a7121d901b8
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/__init__.py
@@ -0,0 +1,13 @@
+from .client import Client
+from .middleware import WSGIApp, Middleware
+from .server import Server
+from .async_server import AsyncServer
+from .async_client import AsyncClient
+from .async_drivers.asgi import ASGIApp
+try:
+ from .async_drivers.tornado import get_tornado_handler
+except ImportError: # pragma: no cover
+ get_tornado_handler = None
+
+__all__ = ['Server', 'WSGIApp', 'Middleware', 'Client',
+ 'AsyncServer', 'ASGIApp', 'get_tornado_handler', 'AsyncClient']
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..72cd800589853ba12d117e85e7427a83f896b985
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_client.py
@@ -0,0 +1,654 @@
+import asyncio
+import signal
+import ssl
+import threading
+
+try:
+ import aiohttp
+except ImportError: # pragma: no cover
+ aiohttp = None
+
+from . import base_client
+from . import exceptions
+from . import packet
+from . import payload
+
+async_signal_handler_set = False
+
+# this set is used to keep references to background tasks to prevent them from
+# being garbage collected mid-execution. Solution taken from
+# https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
+task_reference_holder = set()
+
+
+def async_signal_handler():
+ """SIGINT handler.
+
+ Disconnect all active async clients.
+ """
+ async def _handler(): # pragma: no cover
+ for c in base_client.connected_clients[:]:
+ if c.is_asyncio_based():
+ await c.disconnect()
+
+ # cancel all running tasks
+ tasks = [task for task in asyncio.all_tasks() if task is not
+ asyncio.current_task()]
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ asyncio.get_event_loop().stop()
+
+ asyncio.ensure_future(_handler())
+
+
+class AsyncClient(base_client.BaseClient):
+ """An Engine.IO client for asyncio.
+
+ This class implements a fully compliant Engine.IO web client with support
+ for websocket and long-polling transports, compatible with the asyncio
+ framework on Python 3.5 or newer.
+
+ :param logger: To enable logging set to ``True`` or pass a logger object to
+ use. To disable logging set to ``False``. The default is
+ ``False``. Note that fatal errors are logged even when
+ ``logger`` is ``False``.
+ :param json: An alternative json module to use for encoding and decoding
+ packets. Custom json modules must have ``dumps`` and ``loads``
+ functions that are compatible with the standard library
+ versions.
+ :param request_timeout: A timeout in seconds for requests. The default is
+ 5 seconds.
+ :param http_session: an initialized ``aiohttp.ClientSession`` object to be
+ used when sending requests to the server. Use it if
+ you need to add special client options such as proxy
+ servers, SSL certificates, etc.
+ :param ssl_verify: ``True`` to verify SSL certificates, or ``False`` to
+ skip SSL certificate verification, allowing
+ connections to servers with self signed certificates.
+ The default is ``True``.
+ :param handle_sigint: Set to ``True`` to automatically handle disconnection
+ when the process is interrupted, or to ``False`` to
+ leave interrupt handling to the calling application.
+ Interrupt handling can only be enabled when the
+ client instance is created in the main thread.
+ :param websocket_extra_options: Dictionary containing additional keyword
+ arguments passed to
+ ``aiohttp.ws_connect()``.
+ """
+ def is_asyncio_based(self):
+ return True
+
+ async def connect(self, url, headers=None, transports=None,
+ engineio_path='engine.io'):
+ """Connect to an Engine.IO server.
+
+ :param url: The URL of the Engine.IO server. It can include custom
+ query string parameters if required by the server.
+ :param headers: A dictionary with custom headers to send with the
+ connection request.
+ :param transports: The list of allowed transports. Valid transports
+ are ``'polling'`` and ``'websocket'``. If not
+ given, the polling transport is connected first,
+ then an upgrade to websocket is attempted.
+ :param engineio_path: The endpoint where the Engine.IO server is
+ installed. The default value is appropriate for
+ most cases.
+
+ Note: this method is a coroutine.
+
+ Example usage::
+
+ eio = engineio.Client()
+ await eio.connect('http://localhost:5000')
+ """
+ global async_signal_handler_set
+ if self.handle_sigint and not async_signal_handler_set and \
+ threading.current_thread() == threading.main_thread():
+ try:
+ asyncio.get_event_loop().add_signal_handler(
+ signal.SIGINT, async_signal_handler)
+ except NotImplementedError: # pragma: no cover
+ self.logger.warning('Signal handler is unsupported')
+ async_signal_handler_set = True
+
+ if self.state != 'disconnected':
+ raise ValueError('Client is not in a disconnected state')
+ valid_transports = ['polling', 'websocket']
+ if transports is not None:
+ if isinstance(transports, str):
+ transports = [transports]
+ transports = [transport for transport in transports
+ if transport in valid_transports]
+ if not transports:
+ raise ValueError('No valid transports provided')
+ self.transports = transports or valid_transports
+ self.queue = self.create_queue()
+ return await getattr(self, '_connect_' + self.transports[0])(
+ url, headers or {}, engineio_path)
+
+ async def wait(self):
+ """Wait until the connection with the server ends.
+
+ Client applications can use this function to block the main thread
+ during the life of the connection.
+
+ Note: this method is a coroutine.
+ """
+ if self.read_loop_task:
+ await self.read_loop_task
+
+ async def send(self, data):
+ """Send a message to the server.
+
+ :param data: The data to send to the server. Data can be of type
+ ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
+ or ``dict``, the data will be serialized as JSON.
+
+ Note: this method is a coroutine.
+ """
+ await self._send_packet(packet.Packet(packet.MESSAGE, data=data))
+
+ async def disconnect(self, abort=False):
+ """Disconnect from the server.
+
+ :param abort: If set to ``True``, do not wait for background tasks
+ associated with the connection to end.
+
+ Note: this method is a coroutine.
+ """
+ if self.state == 'connected':
+ await self._send_packet(packet.Packet(packet.CLOSE))
+ await self.queue.put(None)
+ self.state = 'disconnecting'
+ await self._trigger_event('disconnect', run_async=False)
+ if self.current_transport == 'websocket':
+ await self.ws.close()
+ if not abort:
+ await self.read_loop_task
+ self.state = 'disconnected'
+ try:
+ base_client.connected_clients.remove(self)
+ except ValueError: # pragma: no cover
+ pass
+ await self._reset()
+
+ def start_background_task(self, target, *args, **kwargs):
+ """Start a background task.
+
+ This is a utility function that applications can use to start a
+ background task.
+
+ :param target: the target function to execute.
+ :param args: arguments to pass to the function.
+ :param kwargs: keyword arguments to pass to the function.
+
+ The return value is a ``asyncio.Task`` object.
+ """
+ return asyncio.ensure_future(target(*args, **kwargs))
+
+ async def sleep(self, seconds=0):
+ """Sleep for the requested amount of time.
+
+ Note: this method is a coroutine.
+ """
+ return await asyncio.sleep(seconds)
+
+ def create_queue(self):
+ """Create a queue object."""
+ q = asyncio.Queue()
+ q.Empty = asyncio.QueueEmpty
+ return q
+
+ def create_event(self):
+ """Create an event object."""
+ return asyncio.Event()
+
+ async def _reset(self):
+ super()._reset()
+ if not self.external_http: # pragma: no cover
+ if self.http and not self.http.closed:
+ await self.http.close()
+
+ def __del__(self): # pragma: no cover
+ # try to close the aiohttp session if it is still open
+ if self.http and not self.http.closed:
+ try:
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ loop.ensure_future(self.http.close())
+ else:
+ loop.run_until_complete(self.http.close())
+ except:
+ pass
+
+ async def _connect_polling(self, url, headers, engineio_path):
+ """Establish a long-polling connection to the Engine.IO server."""
+ if aiohttp is None: # pragma: no cover
+ self.logger.error('aiohttp not installed -- cannot make HTTP '
+ 'requests!')
+ return
+ self.base_url = self._get_engineio_url(url, engineio_path, 'polling')
+ self.logger.info('Attempting polling connection to ' + self.base_url)
+ r = await self._send_request(
+ 'GET', self.base_url + self._get_url_timestamp(), headers=headers,
+ timeout=self.request_timeout)
+ if r is None or isinstance(r, str):
+ await self._reset()
+ raise exceptions.ConnectionError(
+ r or 'Connection refused by the server')
+ if r.status < 200 or r.status >= 300:
+ await self._reset()
+ try:
+ arg = await r.json()
+ except aiohttp.ClientError:
+ arg = None
+ raise exceptions.ConnectionError(
+ 'Unexpected status code {} in server response'.format(
+ r.status), arg)
+ try:
+ p = payload.Payload(encoded_payload=(await r.read()).decode(
+ 'utf-8'))
+ except ValueError:
+ raise exceptions.ConnectionError(
+ 'Unexpected response from server') from None
+ open_packet = p.packets[0]
+ if open_packet.packet_type != packet.OPEN:
+ raise exceptions.ConnectionError(
+ 'OPEN packet not returned by server')
+ self.logger.info(
+ 'Polling connection accepted with ' + str(open_packet.data))
+ self.sid = open_packet.data['sid']
+ self.upgrades = open_packet.data['upgrades']
+ self.ping_interval = int(open_packet.data['pingInterval']) / 1000.0
+ self.ping_timeout = int(open_packet.data['pingTimeout']) / 1000.0
+ self.current_transport = 'polling'
+ self.base_url += '&sid=' + self.sid
+
+ self.state = 'connected'
+ base_client.connected_clients.append(self)
+ await self._trigger_event('connect', run_async=False)
+
+ for pkt in p.packets[1:]:
+ await self._receive_packet(pkt)
+
+ if 'websocket' in self.upgrades and 'websocket' in self.transports:
+ # attempt to upgrade to websocket
+ if await self._connect_websocket(url, headers, engineio_path):
+ # upgrade to websocket succeeded, we're done here
+ return
+
+ self.write_loop_task = self.start_background_task(self._write_loop)
+ self.read_loop_task = self.start_background_task(
+ self._read_loop_polling)
+
+ async def _connect_websocket(self, url, headers, engineio_path):
+ """Establish or upgrade to a WebSocket connection with the server."""
+ if aiohttp is None: # pragma: no cover
+ self.logger.error('aiohttp package not installed')
+ return False
+ websocket_url = self._get_engineio_url(url, engineio_path,
+ 'websocket')
+ if self.sid:
+ self.logger.info(
+ 'Attempting WebSocket upgrade to ' + websocket_url)
+ upgrade = True
+ websocket_url += '&sid=' + self.sid
+ else:
+ upgrade = False
+ self.base_url = websocket_url
+ self.logger.info(
+ 'Attempting WebSocket connection to ' + websocket_url)
+
+ if self.http is None or self.http.closed: # pragma: no cover
+ self.http = aiohttp.ClientSession()
+
+ # extract any new cookies passed in a header so that they can also be
+ # sent the the WebSocket route
+ cookies = {}
+ for header, value in headers.items():
+ if header.lower() == 'cookie':
+ cookies = dict(
+ [cookie.split('=', 1) for cookie in value.split('; ')])
+ del headers[header]
+ break
+ self.http.cookie_jar.update_cookies(cookies)
+
+ extra_options = {'timeout': self.request_timeout}
+ if not self.ssl_verify:
+ ssl_context = ssl.create_default_context()
+ ssl_context.check_hostname = False
+ ssl_context.verify_mode = ssl.CERT_NONE
+ extra_options['ssl'] = ssl_context
+
+ # combine internally generated options with the ones supplied by the
+ # caller. The caller's options take precedence.
+ headers.update(self.websocket_extra_options.pop('headers', {}))
+ extra_options['headers'] = headers
+ extra_options.update(self.websocket_extra_options)
+
+ try:
+ ws = await self.http.ws_connect(
+ websocket_url + self._get_url_timestamp(), **extra_options)
+ except (aiohttp.client_exceptions.WSServerHandshakeError,
+ aiohttp.client_exceptions.ServerConnectionError,
+ aiohttp.client_exceptions.ClientConnectionError):
+ if upgrade:
+ self.logger.warning(
+ 'WebSocket upgrade failed: connection error')
+ return False
+ else:
+ raise exceptions.ConnectionError('Connection error')
+ if upgrade:
+ p = packet.Packet(packet.PING, data='probe').encode()
+ try:
+ await ws.send_str(p)
+ except Exception as e: # pragma: no cover
+ self.logger.warning(
+ 'WebSocket upgrade failed: unexpected send exception: %s',
+ str(e))
+ return False
+ try:
+ p = (await ws.receive()).data
+ except Exception as e: # pragma: no cover
+ self.logger.warning(
+ 'WebSocket upgrade failed: unexpected recv exception: %s',
+ str(e))
+ return False
+ pkt = packet.Packet(encoded_packet=p)
+ if pkt.packet_type != packet.PONG or pkt.data != 'probe':
+ self.logger.warning(
+ 'WebSocket upgrade failed: no PONG packet')
+ return False
+ p = packet.Packet(packet.UPGRADE).encode()
+ try:
+ await ws.send_str(p)
+ except Exception as e: # pragma: no cover
+ self.logger.warning(
+ 'WebSocket upgrade failed: unexpected send exception: %s',
+ str(e))
+ return False
+ self.current_transport = 'websocket'
+ self.logger.info('WebSocket upgrade was successful')
+ else:
+ try:
+ p = (await ws.receive()).data
+ except Exception as e: # pragma: no cover
+ raise exceptions.ConnectionError(
+ 'Unexpected recv exception: ' + str(e))
+ open_packet = packet.Packet(encoded_packet=p)
+ if open_packet.packet_type != packet.OPEN:
+ raise exceptions.ConnectionError('no OPEN packet')
+ self.logger.info(
+ 'WebSocket connection accepted with ' + str(open_packet.data))
+ self.sid = open_packet.data['sid']
+ self.upgrades = open_packet.data['upgrades']
+ self.ping_interval = int(open_packet.data['pingInterval']) / 1000.0
+ self.ping_timeout = int(open_packet.data['pingTimeout']) / 1000.0
+ self.current_transport = 'websocket'
+
+ self.state = 'connected'
+ base_client.connected_clients.append(self)
+ await self._trigger_event('connect', run_async=False)
+
+ self.ws = ws
+ self.write_loop_task = self.start_background_task(self._write_loop)
+ self.read_loop_task = self.start_background_task(
+ self._read_loop_websocket)
+ return True
+
+ async def _receive_packet(self, pkt):
+ """Handle incoming packets from the server."""
+ packet_name = packet.packet_names[pkt.packet_type] \
+ if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN'
+ self.logger.info(
+ 'Received packet %s data %s', packet_name,
+ pkt.data if not isinstance(pkt.data, bytes) else '')
+ if pkt.packet_type == packet.MESSAGE:
+ await self._trigger_event('message', pkt.data, run_async=True)
+ elif pkt.packet_type == packet.PING:
+ await self._send_packet(packet.Packet(packet.PONG, pkt.data))
+ elif pkt.packet_type == packet.CLOSE:
+ await self.disconnect(abort=True)
+ elif pkt.packet_type == packet.NOOP:
+ pass
+ else:
+ self.logger.error('Received unexpected packet of type %s',
+ pkt.packet_type)
+
+ async def _send_packet(self, pkt):
+ """Queue a packet to be sent to the server."""
+ if self.state != 'connected':
+ return
+ await self.queue.put(pkt)
+ self.logger.info(
+ 'Sending packet %s data %s',
+ packet.packet_names[pkt.packet_type],
+ pkt.data if not isinstance(pkt.data, bytes) else '')
+
+ async def _send_request(
+ self, method, url, headers=None, body=None,
+ timeout=None): # pragma: no cover
+ if self.http is None or self.http.closed:
+ self.http = aiohttp.ClientSession()
+ http_method = getattr(self.http, method.lower())
+
+ try:
+ if not self.ssl_verify:
+ return await http_method(
+ url, headers=headers, data=body,
+ timeout=aiohttp.ClientTimeout(total=timeout), ssl=False)
+ else:
+ return await http_method(
+ url, headers=headers, data=body,
+ timeout=aiohttp.ClientTimeout(total=timeout))
+
+ except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
+ self.logger.info('HTTP %s request to %s failed with error %s.',
+ method, url, exc)
+ return str(exc)
+
+ async def _trigger_event(self, event, *args, **kwargs):
+ """Invoke an event handler."""
+ run_async = kwargs.pop('run_async', False)
+ ret = None
+ if event in self.handlers:
+ if asyncio.iscoroutinefunction(self.handlers[event]) is True:
+ if run_async:
+ task = self.start_background_task(self.handlers[event],
+ *args)
+ task_reference_holder.add(task)
+ task.add_done_callback(task_reference_holder.discard)
+ return task
+ else:
+ try:
+ ret = await self.handlers[event](*args)
+ except asyncio.CancelledError: # pragma: no cover
+ pass
+ except:
+ self.logger.exception(event + ' async handler error')
+ if event == 'connect':
+ # if connect handler raised error we reject the
+ # connection
+ return False
+ else:
+ if run_async:
+ async def async_handler():
+ return self.handlers[event](*args)
+
+ task = self.start_background_task(async_handler)
+ task_reference_holder.add(task)
+ task.add_done_callback(task_reference_holder.discard)
+ return task
+ else:
+ try:
+ ret = self.handlers[event](*args)
+ except:
+ self.logger.exception(event + ' handler error')
+ if event == 'connect':
+ # if connect handler raised error we reject the
+ # connection
+ return False
+ return ret
+
+ async def _read_loop_polling(self):
+ """Read packets by polling the Engine.IO server."""
+ while self.state == 'connected' and self.write_loop_task:
+ self.logger.info(
+ 'Sending polling GET request to ' + self.base_url)
+ r = await self._send_request(
+ 'GET', self.base_url + self._get_url_timestamp(),
+ timeout=max(self.ping_interval, self.ping_timeout) + 5)
+ if r is None or isinstance(r, str):
+ self.logger.warning(
+ r or 'Connection refused by the server, aborting')
+ await self.queue.put(None)
+ break
+ if r.status < 200 or r.status >= 300:
+ self.logger.warning('Unexpected status code %s in server '
+ 'response, aborting', r.status)
+ await self.queue.put(None)
+ break
+ try:
+ p = payload.Payload(encoded_payload=(await r.read()).decode(
+ 'utf-8'))
+ except ValueError:
+ self.logger.warning(
+ 'Unexpected packet from server, aborting')
+ await self.queue.put(None)
+ break
+ for pkt in p.packets:
+ await self._receive_packet(pkt)
+
+ if self.write_loop_task: # pragma: no branch
+ self.logger.info('Waiting for write loop task to end')
+ await self.write_loop_task
+ if self.state == 'connected':
+ await self._trigger_event('disconnect', run_async=False)
+ try:
+ base_client.connected_clients.remove(self)
+ except ValueError: # pragma: no cover
+ pass
+ await self._reset()
+ self.logger.info('Exiting read loop task')
+
+ async def _read_loop_websocket(self):
+ """Read packets from the Engine.IO WebSocket connection."""
+ while self.state == 'connected':
+ p = None
+ try:
+ p = await asyncio.wait_for(
+ self.ws.receive(),
+ timeout=self.ping_interval + self.ping_timeout)
+ if not isinstance(p.data, (str, bytes)): # pragma: no cover
+ self.logger.warning(
+ 'Server sent %s packet data %s, aborting',
+ 'close' if p.type in [aiohttp.WSMsgType.CLOSE,
+ aiohttp.WSMsgType.CLOSING]
+ else str(p.type), str(p.data))
+ await self.queue.put(None)
+ break # the connection is broken
+ p = p.data
+ except asyncio.TimeoutError:
+ self.logger.warning(
+ 'Server has stopped communicating, aborting')
+ await self.queue.put(None)
+ break
+ except aiohttp.client_exceptions.ServerDisconnectedError:
+ self.logger.info(
+ 'Read loop: WebSocket connection was closed, aborting')
+ await self.queue.put(None)
+ break
+ except Exception as e:
+ self.logger.info(
+ 'Unexpected error receiving packet: "%s", aborting',
+ str(e))
+ await self.queue.put(None)
+ break
+ try:
+ pkt = packet.Packet(encoded_packet=p)
+ except Exception as e: # pragma: no cover
+ self.logger.info(
+ 'Unexpected error decoding packet: "%s", aborting', str(e))
+ await self.queue.put(None)
+ break
+ await self._receive_packet(pkt)
+
+ if self.write_loop_task: # pragma: no branch
+ self.logger.info('Waiting for write loop task to end')
+ await self.write_loop_task
+ if self.state == 'connected':
+ await self._trigger_event('disconnect', run_async=False)
+ try:
+ base_client.connected_clients.remove(self)
+ except ValueError: # pragma: no cover
+ pass
+ await self._reset()
+ self.logger.info('Exiting read loop task')
+
+ async def _write_loop(self):
+ """This background task sends packages to the server as they are
+ pushed to the send queue.
+ """
+ while self.state == 'connected':
+ # to simplify the timeout handling, use the maximum of the
+ # ping interval and ping timeout as timeout, with an extra 5
+ # seconds grace period
+ timeout = max(self.ping_interval, self.ping_timeout) + 5
+ packets = None
+ try:
+ packets = [await asyncio.wait_for(self.queue.get(), timeout)]
+ except (self.queue.Empty, asyncio.TimeoutError):
+ self.logger.error('packet queue is empty, aborting')
+ break
+ except asyncio.CancelledError: # pragma: no cover
+ break
+ if packets == [None]:
+ self.queue.task_done()
+ packets = []
+ else:
+ while True:
+ try:
+ packets.append(self.queue.get_nowait())
+ except self.queue.Empty:
+ break
+ if packets[-1] is None:
+ packets = packets[:-1]
+ self.queue.task_done()
+ break
+ if not packets:
+ # empty packet list returned -> connection closed
+ break
+ if self.current_transport == 'polling':
+ p = payload.Payload(packets=packets)
+ r = await self._send_request(
+ 'POST', self.base_url, body=p.encode(),
+ headers={'Content-Type': 'text/plain'},
+ timeout=self.request_timeout)
+ for pkt in packets:
+ self.queue.task_done()
+ if r is None or isinstance(r, str):
+ self.logger.warning(
+ r or 'Connection refused by the server, aborting')
+ break
+ if r.status < 200 or r.status >= 300:
+ self.logger.warning('Unexpected status code %s in server '
+ 'response, aborting', r.status)
+ self.write_loop_task = None
+ break
+ else:
+ # websocket
+ try:
+ for pkt in packets:
+ if pkt.binary:
+ await self.ws.send_bytes(pkt.encode())
+ else:
+ await self.ws.send_str(pkt.encode())
+ self.queue.task_done()
+ except (aiohttp.client_exceptions.ServerDisconnectedError,
+ BrokenPipeError, OSError):
+ self.logger.info(
+ 'Write loop: WebSocket connection was closed, '
+ 'aborting')
+ break
+ self.logger.info('Exiting write loop task')
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7763830ccc7563ea35179a6f91bffc3bd9741a3
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_server.py
@@ -0,0 +1,566 @@
+import asyncio
+import urllib
+
+from . import base_server
+from . import exceptions
+from . import packet
+from . import async_socket
+
+# this set is used to keep references to background tasks to prevent them from
+# being garbage collected mid-execution. Solution taken from
+# https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
+task_reference_holder = set()
+
+
+class AsyncServer(base_server.BaseServer):
+ """An Engine.IO server for asyncio.
+
+ This class implements a fully compliant Engine.IO web server with support
+ for websocket and long-polling transports, compatible with the asyncio
+ framework on Python 3.5 or newer.
+
+ :param async_mode: The asynchronous model to use. See the Deployment
+ section in the documentation for a description of the
+ available options. Valid async modes are "aiohttp",
+ "sanic", "tornado" and "asgi". If this argument is not
+ given, "aiohttp" is tried first, followed by "sanic",
+ "tornado", and finally "asgi". The first async mode that
+ has all its dependencies installed is the one that is
+ chosen.
+ :param ping_interval: The interval in seconds at which the server pings
+ the client. The default is 25 seconds. For advanced
+ control, a two element tuple can be given, where
+ the first number is the ping interval and the second
+ is a grace period added by the server.
+ :param ping_timeout: The time in seconds that the client waits for the
+ server to respond before disconnecting. The default
+ is 20 seconds.
+ :param max_http_buffer_size: The maximum size that is accepted for incoming
+ messages. The default is 1,000,000 bytes. In
+ spite of its name, the value set in this
+ argument is enforced for HTTP long-polling and
+ WebSocket connections.
+ :param allow_upgrades: Whether to allow transport upgrades or not.
+ :param http_compression: Whether to compress packages when using the
+ polling transport.
+ :param compression_threshold: Only compress messages when their byte size
+ is greater than this value.
+ :param cookie: If set to a string, it is the name of the HTTP cookie the
+ server sends back tot he client containing the client
+ session id. If set to a dictionary, the ``'name'`` key
+ contains the cookie name and other keys define cookie
+ attributes, where the value of each attribute can be a
+ string, a callable with no arguments, or a boolean. If set
+ to ``None`` (the default), a cookie is not sent to the
+ client.
+ :param cors_allowed_origins: Origin or list of origins that are allowed to
+ connect to this server. Only the same origin
+ is allowed by default. Set this argument to
+ ``'*'`` to allow all origins, or to ``[]`` to
+ disable CORS handling.
+ :param cors_credentials: Whether credentials (cookies, authentication) are
+ allowed in requests to this server.
+ :param logger: To enable logging set to ``True`` or pass a logger object to
+ use. To disable logging set to ``False``. Note that fatal
+ errors are logged even when ``logger`` is ``False``.
+ :param json: An alternative json module to use for encoding and decoding
+ packets. Custom json modules must have ``dumps`` and ``loads``
+ functions that are compatible with the standard library
+ versions.
+ :param async_handlers: If set to ``True``, run message event handlers in
+ non-blocking threads. To run handlers synchronously,
+ set to ``False``. The default is ``True``.
+ :param transports: The list of allowed transports. Valid transports
+ are ``'polling'`` and ``'websocket'``. Defaults to
+ ``['polling', 'websocket']``.
+ :param kwargs: Reserved for future extensions, any additional parameters
+ given as keyword arguments will be silently ignored.
+ """
+ def is_asyncio_based(self):
+ return True
+
+ def async_modes(self):
+ return ['aiohttp', 'sanic', 'tornado', 'asgi']
+
+ def attach(self, app, engineio_path='engine.io'):
+ """Attach the Engine.IO server to an application."""
+ engineio_path = engineio_path.strip('/')
+ self._async['create_route'](app, self, '/{}/'.format(engineio_path))
+
+ async def send(self, sid, data):
+ """Send a message to a client.
+
+ :param sid: The session id of the recipient client.
+ :param data: The data to send to the client. Data can be of type
+ ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
+ or ``dict``, the data will be serialized as JSON.
+
+ Note: this method is a coroutine.
+ """
+ await self.send_packet(sid, packet.Packet(packet.MESSAGE, data=data))
+
+ async def send_packet(self, sid, pkt):
+ """Send a raw packet to a client.
+
+ :param sid: The session id of the recipient client.
+ :param pkt: The packet to send to the client.
+
+ Note: this method is a coroutine.
+ """
+ try:
+ socket = self._get_socket(sid)
+ except KeyError:
+ # the socket is not available
+ self.logger.warning('Cannot send to sid %s', sid)
+ return
+ await socket.send(pkt)
+
+ async def get_session(self, sid):
+ """Return the user session for a client.
+
+ :param sid: The session id of the client.
+
+ The return value is a dictionary. Modifications made to this
+ dictionary are not guaranteed to be preserved. If you want to modify
+ the user session, use the ``session`` context manager instead.
+ """
+ socket = self._get_socket(sid)
+ return socket.session
+
+ async def save_session(self, sid, session):
+ """Store the user session for a client.
+
+ :param sid: The session id of the client.
+ :param session: The session dictionary.
+ """
+ socket = self._get_socket(sid)
+ socket.session = session
+
+ def session(self, sid):
+ """Return the user session for a client with context manager syntax.
+
+ :param sid: The session id of the client.
+
+ This is a context manager that returns the user session dictionary for
+ the client. Any changes that are made to this dictionary inside the
+ context manager block are saved back to the session. Example usage::
+
+ @eio.on('connect')
+ def on_connect(sid, environ):
+ username = authenticate_user(environ)
+ if not username:
+ return False
+ with eio.session(sid) as session:
+ session['username'] = username
+
+ @eio.on('message')
+ def on_message(sid, msg):
+ async with eio.session(sid) as session:
+ print('received message from ', session['username'])
+ """
+ class _session_context_manager(object):
+ def __init__(self, server, sid):
+ self.server = server
+ self.sid = sid
+ self.session = None
+
+ async def __aenter__(self):
+ self.session = await self.server.get_session(sid)
+ return self.session
+
+ async def __aexit__(self, *args):
+ await self.server.save_session(sid, self.session)
+
+ return _session_context_manager(self, sid)
+
+ async def disconnect(self, sid=None):
+ """Disconnect a client.
+
+ :param sid: The session id of the client to close. If this parameter
+ is not given, then all clients are closed.
+
+ Note: this method is a coroutine.
+ """
+ if sid is not None:
+ try:
+ socket = self._get_socket(sid)
+ except KeyError: # pragma: no cover
+ # the socket was already closed or gone
+ pass
+ else:
+ await socket.close()
+ if sid in self.sockets: # pragma: no cover
+ del self.sockets[sid]
+ else:
+ await asyncio.wait([asyncio.create_task(client.close())
+ for client in self.sockets.values()])
+ self.sockets = {}
+
+ async def handle_request(self, *args, **kwargs):
+ """Handle an HTTP request from the client.
+
+ This is the entry point of the Engine.IO application. This function
+ returns the HTTP response to deliver to the client.
+
+ Note: this method is a coroutine.
+ """
+ translate_request = self._async['translate_request']
+ if asyncio.iscoroutinefunction(translate_request):
+ environ = await translate_request(*args, **kwargs)
+ else:
+ environ = translate_request(*args, **kwargs)
+
+ if self.cors_allowed_origins != []:
+ # Validate the origin header if present
+ # This is important for WebSocket more than for HTTP, since
+ # browsers only apply CORS controls to HTTP.
+ origin = environ.get('HTTP_ORIGIN')
+ if origin:
+ allowed_origins = self._cors_allowed_origins(environ)
+ if allowed_origins is not None and origin not in \
+ allowed_origins:
+ self._log_error_once(
+ origin + ' is not an accepted origin.', 'bad-origin')
+ return await self._make_response(
+ self._bad_request(
+ origin + ' is not an accepted origin.'),
+ environ)
+
+ method = environ['REQUEST_METHOD']
+ query = urllib.parse.parse_qs(environ.get('QUERY_STRING', ''))
+
+ sid = query['sid'][0] if 'sid' in query else None
+ jsonp = False
+ jsonp_index = None
+
+ # make sure the client uses an allowed transport
+ transport = query.get('transport', ['polling'])[0]
+ if transport not in self.transports:
+ self._log_error_once('Invalid transport', 'bad-transport')
+ return await self._make_response(
+ self._bad_request('Invalid transport'), environ)
+
+ # make sure the client speaks a compatible Engine.IO version
+ sid = query['sid'][0] if 'sid' in query else None
+ if sid is None and query.get('EIO') != ['4']:
+ self._log_error_once(
+ 'The client is using an unsupported version of the Socket.IO '
+ 'or Engine.IO protocols', 'bad-version'
+ )
+ return await self._make_response(self._bad_request(
+ 'The client is using an unsupported version of the Socket.IO '
+ 'or Engine.IO protocols'
+ ), environ)
+
+ if 'j' in query:
+ jsonp = True
+ try:
+ jsonp_index = int(query['j'][0])
+ except (ValueError, KeyError, IndexError):
+ # Invalid JSONP index number
+ pass
+
+ if jsonp and jsonp_index is None:
+ self._log_error_once('Invalid JSONP index number',
+ 'bad-jsonp-index')
+ r = self._bad_request('Invalid JSONP index number')
+ elif method == 'GET':
+ if sid is None:
+ # transport must be one of 'polling' or 'websocket'.
+ # if 'websocket', the HTTP_UPGRADE header must match.
+ upgrade_header = environ.get('HTTP_UPGRADE').lower() \
+ if 'HTTP_UPGRADE' in environ else None
+ if transport == 'polling' \
+ or transport == upgrade_header == 'websocket':
+ r = await self._handle_connect(environ, transport,
+ jsonp_index)
+ else:
+ self._log_error_once('Invalid websocket upgrade',
+ 'bad-upgrade')
+ r = self._bad_request('Invalid websocket upgrade')
+ else:
+ if sid not in self.sockets:
+ self._log_error_once('Invalid session ' + sid, 'bad-sid')
+ r = self._bad_request('Invalid session ' + sid)
+ else:
+ socket = self._get_socket(sid)
+ try:
+ packets = await socket.handle_get_request(environ)
+ if isinstance(packets, list):
+ r = self._ok(packets, jsonp_index=jsonp_index)
+ else:
+ r = packets
+ except exceptions.EngineIOError:
+ if sid in self.sockets: # pragma: no cover
+ await self.disconnect(sid)
+ r = self._bad_request()
+ if sid in self.sockets and self.sockets[sid].closed:
+ del self.sockets[sid]
+ elif method == 'POST':
+ if sid is None or sid not in self.sockets:
+ self._log_error_once('Invalid session ' + sid, 'bad-sid')
+ r = self._bad_request('Invalid session ' + sid)
+ else:
+ socket = self._get_socket(sid)
+ try:
+ await socket.handle_post_request(environ)
+ r = self._ok(jsonp_index=jsonp_index)
+ except exceptions.EngineIOError:
+ if sid in self.sockets: # pragma: no cover
+ await self.disconnect(sid)
+ r = self._bad_request()
+ except: # pragma: no cover
+ # for any other unexpected errors, we log the error
+ # and keep going
+ self.logger.exception('post request handler error')
+ r = self._ok(jsonp_index=jsonp_index)
+ elif method == 'OPTIONS':
+ r = self._ok()
+ else:
+ self.logger.warning('Method %s not supported', method)
+ r = self._method_not_found()
+ if not isinstance(r, dict):
+ return r
+ if self.http_compression and \
+ len(r['response']) >= self.compression_threshold:
+ encodings = [e.split(';')[0].strip() for e in
+ environ.get('HTTP_ACCEPT_ENCODING', '').split(',')]
+ for encoding in encodings:
+ if encoding in self.compression_methods:
+ r['response'] = \
+ getattr(self, '_' + encoding)(r['response'])
+ r['headers'] += [('Content-Encoding', encoding)]
+ break
+ return await self._make_response(r, environ)
+
+ async def shutdown(self):
+ """Stop Socket.IO background tasks.
+
+ This method stops background activity initiated by the Socket.IO
+ server. It must be called before shutting down the web server.
+ """
+ self.logger.info('Socket.IO is shutting down')
+ if self.service_task_event: # pragma: no cover
+ self.service_task_event.set()
+ await self.service_task_handle
+ self.service_task_handle = None
+
+ def start_background_task(self, target, *args, **kwargs):
+ """Start a background task using the appropriate async model.
+
+ This is a utility function that applications can use to start a
+ background task using the method that is compatible with the
+ selected async mode.
+
+ :param target: the target function to execute.
+ :param args: arguments to pass to the function.
+ :param kwargs: keyword arguments to pass to the function.
+
+ The return value is a ``asyncio.Task`` object.
+ """
+ return asyncio.ensure_future(target(*args, **kwargs))
+
+ async def sleep(self, seconds=0):
+ """Sleep for the requested amount of time using the appropriate async
+ model.
+
+ This is a utility function that applications can use to put a task to
+ sleep without having to worry about using the correct call for the
+ selected async mode.
+
+ Note: this method is a coroutine.
+ """
+ return await asyncio.sleep(seconds)
+
+ def create_queue(self, *args, **kwargs):
+ """Create a queue object using the appropriate async model.
+
+ This is a utility function that applications can use to create a queue
+ without having to worry about using the correct call for the selected
+ async mode. For asyncio based async modes, this returns an instance of
+ ``asyncio.Queue``.
+ """
+ return asyncio.Queue(*args, **kwargs)
+
+ def get_queue_empty_exception(self):
+ """Return the queue empty exception for the appropriate async model.
+
+ This is a utility function that applications can use to work with a
+ queue without having to worry about using the correct call for the
+ selected async mode. For asyncio based async modes, this returns an
+ instance of ``asyncio.QueueEmpty``.
+ """
+ return asyncio.QueueEmpty
+
+ def create_event(self, *args, **kwargs):
+ """Create an event object using the appropriate async model.
+
+ This is a utility function that applications can use to create an
+ event without having to worry about using the correct call for the
+ selected async mode. For asyncio based async modes, this returns
+ an instance of ``asyncio.Event``.
+ """
+ return asyncio.Event(*args, **kwargs)
+
+ async def _make_response(self, response_dict, environ):
+ cors_headers = self._cors_headers(environ)
+ make_response = self._async['make_response']
+ if asyncio.iscoroutinefunction(make_response):
+ response = await make_response(
+ response_dict['status'],
+ response_dict['headers'] + cors_headers,
+ response_dict['response'], environ)
+ else:
+ response = make_response(
+ response_dict['status'],
+ response_dict['headers'] + cors_headers,
+ response_dict['response'], environ)
+ return response
+
+ async def _handle_connect(self, environ, transport, jsonp_index=None):
+ """Handle a client connection request."""
+ if self.start_service_task:
+ # start the service task to monitor connected clients
+ self.start_service_task = False
+ self.service_task_handle = self.start_background_task(
+ self._service_task)
+
+ sid = self.generate_id()
+ s = async_socket.AsyncSocket(self, sid)
+ self.sockets[sid] = s
+
+ pkt = packet.Packet(
+ packet.OPEN, {'sid': sid,
+ 'upgrades': self._upgrades(sid, transport),
+ 'pingTimeout': int(self.ping_timeout * 1000),
+ 'pingInterval': int(self.ping_interval * 1000)})
+ await s.send(pkt)
+ s.schedule_ping()
+
+ ret = await self._trigger_event('connect', sid, environ,
+ run_async=False)
+ if ret is not None and ret is not True:
+ del self.sockets[sid]
+ self.logger.warning('Application rejected connection')
+ return self._unauthorized(ret or None)
+
+ if transport == 'websocket':
+ ret = await s.handle_get_request(environ)
+ if s.closed and sid in self.sockets:
+ # websocket connection ended, so we are done
+ del self.sockets[sid]
+ return ret
+ else:
+ s.connected = True
+ headers = None
+ if self.cookie:
+ if isinstance(self.cookie, dict):
+ headers = [(
+ 'Set-Cookie',
+ self._generate_sid_cookie(sid, self.cookie)
+ )]
+ else:
+ headers = [(
+ 'Set-Cookie',
+ self._generate_sid_cookie(sid, {
+ 'name': self.cookie, 'path': '/', 'SameSite': 'Lax'
+ })
+ )]
+ try:
+ return self._ok(await s.poll(), headers=headers,
+ jsonp_index=jsonp_index)
+ except exceptions.QueueEmpty:
+ return self._bad_request()
+
+ async def _trigger_event(self, event, *args, **kwargs):
+ """Invoke an event handler."""
+ run_async = kwargs.pop('run_async', False)
+ ret = None
+ if event in self.handlers:
+ if asyncio.iscoroutinefunction(self.handlers[event]):
+ async def run_async_handler():
+ try:
+ return await self.handlers[event](*args)
+ except asyncio.CancelledError: # pragma: no cover
+ pass
+ except:
+ self.logger.exception(event + ' async handler error')
+ if event == 'connect':
+ # if connect handler raised error we reject the
+ # connection
+ return False
+
+ if run_async:
+ ret = self.start_background_task(run_async_handler)
+ task_reference_holder.add(ret)
+ ret.add_done_callback(task_reference_holder.discard)
+ else:
+ ret = await run_async_handler()
+ else:
+ async def run_sync_handler():
+ try:
+ return self.handlers[event](*args)
+ except:
+ self.logger.exception(event + ' handler error')
+ if event == 'connect':
+ # if connect handler raised error we reject the
+ # connection
+ return False
+
+ if run_async:
+ ret = self.start_background_task(run_sync_handler)
+ task_reference_holder.add(ret)
+ ret.add_done_callback(task_reference_holder.discard)
+ else:
+ ret = await run_sync_handler()
+ return ret
+
+ async def _service_task(self): # pragma: no cover
+ """Monitor connected clients and clean up those that time out."""
+ self.service_task_event = self.create_event()
+ while not self.service_task_event.is_set():
+ if len(self.sockets) == 0:
+ # nothing to do
+ try:
+ await asyncio.wait_for(self.service_task_event.wait(),
+ timeout=self.ping_timeout)
+ except asyncio.TimeoutError:
+ break
+ continue
+
+ # go through the entire client list in a ping interval cycle
+ sleep_interval = self.ping_timeout / len(self.sockets)
+
+ try:
+ # iterate over the current clients
+ for s in self.sockets.copy().values():
+ if s.closed:
+ try:
+ del self.sockets[s.sid]
+ except KeyError:
+ # the socket could have also been removed by
+ # the _get_socket() method from another thread
+ pass
+ elif not s.closing:
+ await s.check_ping_timeout()
+ try:
+ await asyncio.wait_for(self.service_task_event.wait(),
+ timeout=sleep_interval)
+ except asyncio.TimeoutError:
+ raise KeyboardInterrupt()
+ except (
+ SystemExit,
+ KeyboardInterrupt,
+ asyncio.CancelledError,
+ GeneratorExit,
+ ):
+ self.logger.info('service task canceled')
+ break
+ except:
+ if asyncio.get_event_loop().is_closed():
+ self.logger.info('event loop is closed, exiting service '
+ 'task')
+ break
+
+ # an unexpected exception has occurred, log it and continue
+ self.logger.exception('service task exception')
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_socket.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_socket.py
new file mode 100644
index 0000000000000000000000000000000000000000..75776ef67859b1adb27d710f35d0fffb0a6f3013
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/async_socket.py
@@ -0,0 +1,254 @@
+import asyncio
+import sys
+import time
+
+from . import base_socket
+from . import exceptions
+from . import packet
+from . import payload
+
+
+class AsyncSocket(base_socket.BaseSocket):
+ async def poll(self):
+ """Wait for packets to send to the client."""
+ try:
+ packets = [await asyncio.wait_for(
+ self.queue.get(),
+ self.server.ping_interval + self.server.ping_timeout)]
+ self.queue.task_done()
+ except (asyncio.TimeoutError, asyncio.CancelledError):
+ raise exceptions.QueueEmpty()
+ if packets == [None]:
+ return []
+ while True:
+ try:
+ pkt = self.queue.get_nowait()
+ self.queue.task_done()
+ if pkt is None:
+ self.queue.put_nowait(None)
+ break
+ packets.append(pkt)
+ except asyncio.QueueEmpty:
+ break
+ return packets
+
+ async def receive(self, pkt):
+ """Receive packet from the client."""
+ self.server.logger.info('%s: Received packet %s data %s',
+ self.sid, packet.packet_names[pkt.packet_type],
+ pkt.data if not isinstance(pkt.data, bytes)
+ else '')
+ if pkt.packet_type == packet.PONG:
+ self.schedule_ping()
+ elif pkt.packet_type == packet.MESSAGE:
+ await self.server._trigger_event(
+ 'message', self.sid, pkt.data,
+ run_async=self.server.async_handlers)
+ elif pkt.packet_type == packet.UPGRADE:
+ await self.send(packet.Packet(packet.NOOP))
+ elif pkt.packet_type == packet.CLOSE:
+ await self.close(wait=False, abort=True)
+ else:
+ raise exceptions.UnknownPacketError()
+
+ async def check_ping_timeout(self):
+ """Make sure the client is still sending pings."""
+ if self.closed:
+ raise exceptions.SocketIsClosedError()
+ if self.last_ping and \
+ time.time() - self.last_ping > self.server.ping_timeout:
+ self.server.logger.info('%s: Client is gone, closing socket',
+ self.sid)
+ # Passing abort=False here will cause close() to write a
+ # CLOSE packet. This has the effect of updating half-open sockets
+ # to their correct state of disconnected
+ await self.close(wait=False, abort=False)
+ return False
+ return True
+
+ async def send(self, pkt):
+ """Send a packet to the client."""
+ if not await self.check_ping_timeout():
+ return
+ else:
+ await self.queue.put(pkt)
+ self.server.logger.info('%s: Sending packet %s data %s',
+ self.sid, packet.packet_names[pkt.packet_type],
+ pkt.data if not isinstance(pkt.data, bytes)
+ else '')
+
+ async def handle_get_request(self, environ):
+ """Handle a long-polling GET request from the client."""
+ connections = [
+ s.strip()
+ for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
+ transport = environ.get('HTTP_UPGRADE', '').lower()
+ if 'upgrade' in connections and transport in self.upgrade_protocols:
+ self.server.logger.info('%s: Received request to upgrade to %s',
+ self.sid, transport)
+ return await getattr(self, '_upgrade_' + transport)(environ)
+ if self.upgrading or self.upgraded:
+ # we are upgrading to WebSocket, do not return any more packets
+ # through the polling endpoint
+ return [packet.Packet(packet.NOOP)]
+ try:
+ packets = await self.poll()
+ except exceptions.QueueEmpty:
+ exc = sys.exc_info()
+ await self.close(wait=False)
+ raise exc[1].with_traceback(exc[2])
+ return packets
+
+ async def handle_post_request(self, environ):
+ """Handle a long-polling POST request from the client."""
+ length = int(environ.get('CONTENT_LENGTH', '0'))
+ if length > self.server.max_http_buffer_size:
+ raise exceptions.ContentTooLongError()
+ else:
+ body = (await environ['wsgi.input'].read(length)).decode('utf-8')
+ p = payload.Payload(encoded_payload=body)
+ for pkt in p.packets:
+ await self.receive(pkt)
+
+ async def close(self, wait=True, abort=False):
+ """Close the socket connection."""
+ if not self.closed and not self.closing:
+ self.closing = True
+ await self.server._trigger_event('disconnect', self.sid)
+ if not abort:
+ await self.send(packet.Packet(packet.CLOSE))
+ self.closed = True
+ if wait:
+ await self.queue.join()
+
+ def schedule_ping(self):
+ self.server.start_background_task(self._send_ping)
+
+ async def _send_ping(self):
+ self.last_ping = None
+ await asyncio.sleep(self.server.ping_interval)
+ if not self.closing and not self.closed:
+ self.last_ping = time.time()
+ await self.send(packet.Packet(packet.PING))
+
+ async def _upgrade_websocket(self, environ):
+ """Upgrade the connection from polling to websocket."""
+ if self.upgraded:
+ raise IOError('Socket has been upgraded already')
+ if self.server._async['websocket'] is None:
+ # the selected async mode does not support websocket
+ return self.server._bad_request()
+ ws = self.server._async['websocket'](
+ self._websocket_handler, self.server)
+ return await ws(environ)
+
+ async def _websocket_handler(self, ws):
+ """Engine.IO handler for websocket transport."""
+ async def websocket_wait():
+ data = await ws.wait()
+ if data and len(data) > self.server.max_http_buffer_size:
+ raise ValueError('packet is too large')
+ return data
+
+ if self.connected:
+ # the socket was already connected, so this is an upgrade
+ self.upgrading = True # hold packet sends during the upgrade
+
+ try:
+ pkt = await websocket_wait()
+ except IOError: # pragma: no cover
+ return
+ decoded_pkt = packet.Packet(encoded_packet=pkt)
+ if decoded_pkt.packet_type != packet.PING or \
+ decoded_pkt.data != 'probe':
+ self.server.logger.info(
+ '%s: Failed websocket upgrade, no PING packet', self.sid)
+ self.upgrading = False
+ return
+ await ws.send(packet.Packet(packet.PONG, data='probe').encode())
+ await self.queue.put(packet.Packet(packet.NOOP)) # end poll
+
+ try:
+ pkt = await websocket_wait()
+ except IOError: # pragma: no cover
+ self.upgrading = False
+ return
+ decoded_pkt = packet.Packet(encoded_packet=pkt)
+ if decoded_pkt.packet_type != packet.UPGRADE:
+ self.upgraded = False
+ self.server.logger.info(
+ ('%s: Failed websocket upgrade, expected UPGRADE packet, '
+ 'received %s instead.'),
+ self.sid, pkt)
+ self.upgrading = False
+ return
+ self.upgraded = True
+ self.upgrading = False
+ else:
+ self.connected = True
+ self.upgraded = True
+
+ # start separate writer thread
+ async def writer():
+ while True:
+ packets = None
+ try:
+ packets = await self.poll()
+ except exceptions.QueueEmpty:
+ break
+ if not packets:
+ # empty packet list returned -> connection closed
+ break
+ try:
+ for pkt in packets:
+ await ws.send(pkt.encode())
+ except:
+ break
+ await ws.close()
+
+ writer_task = asyncio.ensure_future(writer())
+
+ self.server.logger.info(
+ '%s: Upgrade to websocket successful', self.sid)
+
+ while True:
+ p = None
+ wait_task = asyncio.ensure_future(websocket_wait())
+ try:
+ p = await asyncio.wait_for(
+ wait_task,
+ self.server.ping_interval + self.server.ping_timeout)
+ except asyncio.CancelledError: # pragma: no cover
+ # there is a bug (https://bugs.python.org/issue30508) in
+ # asyncio that causes a "Task exception never retrieved" error
+ # to appear when wait_task raises an exception before it gets
+ # cancelled. Calling wait_task.exception() prevents the error
+ # from being issued in Python 3.6, but causes other errors in
+ # other versions, so we run it with all errors suppressed and
+ # hope for the best.
+ try:
+ wait_task.exception()
+ except:
+ pass
+ break
+ except:
+ break
+ if p is None:
+ # connection closed by client
+ break
+ pkt = packet.Packet(encoded_packet=p)
+ try:
+ await self.receive(pkt)
+ except exceptions.UnknownPacketError: # pragma: no cover
+ pass
+ except exceptions.SocketIsClosedError: # pragma: no cover
+ self.server.logger.info('Receive error -- socket is closed')
+ break
+ except: # pragma: no cover
+ # if we get an unexpected exception we log the error and exit
+ # the connection properly
+ self.server.logger.exception('Unknown receive error')
+
+ await self.queue.put(None) # unlock the writer task so it can exit
+ await asyncio.wait_for(writer_task, timeout=None)
+ await self.close(wait=False, abort=True)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..6381be20c8ec8ea9c5b3ec44b1badf0caee6c407
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_client.py
@@ -0,0 +1,146 @@
+import logging
+import signal
+import threading
+import time
+import urllib
+from . import packet
+
+default_logger = logging.getLogger('engineio.client')
+connected_clients = []
+
+
+def signal_handler(sig, frame):
+ """SIGINT handler.
+
+ Disconnect all active clients and then invoke the original signal handler.
+ """
+ for client in connected_clients[:]:
+ if not client.is_asyncio_based():
+ client.disconnect()
+ if callable(original_signal_handler):
+ return original_signal_handler(sig, frame)
+ else: # pragma: no cover
+ # Handle case where no original SIGINT handler was present.
+ return signal.default_int_handler(sig, frame)
+
+
+original_signal_handler = None
+
+
+class BaseClient:
+ event_names = ['connect', 'disconnect', 'message']
+
+ def __init__(self, logger=False, json=None, request_timeout=5,
+ http_session=None, ssl_verify=True, handle_sigint=True,
+ websocket_extra_options=None):
+ global original_signal_handler
+ if handle_sigint and original_signal_handler is None and \
+ threading.current_thread() == threading.main_thread():
+ original_signal_handler = signal.signal(signal.SIGINT,
+ signal_handler)
+ self.handlers = {}
+ self.base_url = None
+ self.transports = None
+ self.current_transport = None
+ self.sid = None
+ self.upgrades = None
+ self.ping_interval = None
+ self.ping_timeout = None
+ self.http = http_session
+ self.external_http = http_session is not None
+ self.handle_sigint = handle_sigint
+ self.ws = None
+ self.read_loop_task = None
+ self.write_loop_task = None
+ self.queue = None
+ self.state = 'disconnected'
+ self.ssl_verify = ssl_verify
+ self.websocket_extra_options = websocket_extra_options or {}
+
+ if json is not None:
+ packet.Packet.json = json
+ if not isinstance(logger, bool):
+ self.logger = logger
+ else:
+ self.logger = default_logger
+ if self.logger.level == logging.NOTSET:
+ if logger:
+ self.logger.setLevel(logging.INFO)
+ else:
+ self.logger.setLevel(logging.ERROR)
+ self.logger.addHandler(logging.StreamHandler())
+
+ self.request_timeout = request_timeout
+
+ def is_asyncio_based(self):
+ return False
+
+ def on(self, event, handler=None):
+ """Register an event handler.
+
+ :param event: The event name. Can be ``'connect'``, ``'message'`` or
+ ``'disconnect'``.
+ :param handler: The function that should be invoked to handle the
+ event. When this parameter is not given, the method
+ acts as a decorator for the handler function.
+
+ Example usage::
+
+ # as a decorator:
+ @eio.on('connect')
+ def connect_handler():
+ print('Connection request')
+
+ # as a method:
+ def message_handler(msg):
+ print('Received message: ', msg)
+ eio.send('response')
+ eio.on('message', message_handler)
+ """
+ if event not in self.event_names:
+ raise ValueError('Invalid event')
+
+ def set_handler(handler):
+ self.handlers[event] = handler
+ return handler
+
+ if handler is None:
+ return set_handler
+ set_handler(handler)
+
+ def transport(self):
+ """Return the name of the transport currently in use.
+
+ The possible values returned by this function are ``'polling'`` and
+ ``'websocket'``.
+ """
+ return self.current_transport
+
+ def _reset(self):
+ self.state = 'disconnected'
+ self.sid = None
+
+ def _get_engineio_url(self, url, engineio_path, transport):
+ """Generate the Engine.IO connection URL."""
+ engineio_path = engineio_path.strip('/')
+ parsed_url = urllib.parse.urlparse(url)
+
+ if transport == 'polling':
+ scheme = 'http'
+ elif transport == 'websocket':
+ scheme = 'ws'
+ else: # pragma: no cover
+ raise ValueError('invalid transport')
+ if parsed_url.scheme in ['https', 'wss']:
+ scheme += 's'
+
+ return ('{scheme}://{netloc}/{path}/?{query}'
+ '{sep}transport={transport}&EIO=4').format(
+ scheme=scheme, netloc=parsed_url.netloc,
+ path=engineio_path, query=parsed_url.query,
+ sep='&' if parsed_url.query else '',
+ transport=transport)
+
+ def _get_url_timestamp(self):
+ """Generate the Engine.IO query string timestamp."""
+ return '&t=' + str(time.time())
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..c32cb1416a66058b69b7bea60f9f6152181acf08
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_server.py
@@ -0,0 +1,338 @@
+import base64
+import gzip
+import importlib
+import io
+import logging
+import secrets
+import zlib
+
+from . import packet
+from . import payload
+
+default_logger = logging.getLogger('engineio.server')
+
+
+class BaseServer:
+ compression_methods = ['gzip', 'deflate']
+ event_names = ['connect', 'disconnect', 'message']
+ valid_transports = ['polling', 'websocket']
+ _default_monitor_clients = True
+ sequence_number = 0
+
+ def __init__(self, async_mode=None, ping_interval=25, ping_timeout=20,
+ max_http_buffer_size=1000000, allow_upgrades=True,
+ http_compression=True, compression_threshold=1024,
+ cookie=None, cors_allowed_origins=None,
+ cors_credentials=True, logger=False, json=None,
+ async_handlers=True, monitor_clients=None, transports=None,
+ **kwargs):
+ self.ping_timeout = ping_timeout
+ if isinstance(ping_interval, tuple):
+ self.ping_interval = ping_interval[0]
+ self.ping_interval_grace_period = ping_interval[1]
+ else:
+ self.ping_interval = ping_interval
+ self.ping_interval_grace_period = 0
+ self.max_http_buffer_size = max_http_buffer_size
+ self.allow_upgrades = allow_upgrades
+ self.http_compression = http_compression
+ self.compression_threshold = compression_threshold
+ self.cookie = cookie
+ self.cors_allowed_origins = cors_allowed_origins
+ self.cors_credentials = cors_credentials
+ self.async_handlers = async_handlers
+ self.sockets = {}
+ self.handlers = {}
+ self.log_message_keys = set()
+ self.start_service_task = monitor_clients \
+ if monitor_clients is not None else self._default_monitor_clients
+ self.service_task_handle = None
+ self.service_task_event = None
+ if json is not None:
+ packet.Packet.json = json
+ if not isinstance(logger, bool):
+ self.logger = logger
+ else:
+ self.logger = default_logger
+ if self.logger.level == logging.NOTSET:
+ if logger:
+ self.logger.setLevel(logging.INFO)
+ else:
+ self.logger.setLevel(logging.ERROR)
+ self.logger.addHandler(logging.StreamHandler())
+ modes = self.async_modes()
+ if async_mode is not None:
+ modes = [async_mode] if async_mode in modes else []
+ self._async = None
+ self.async_mode = None
+ for mode in modes:
+ try:
+ self._async = importlib.import_module(
+ 'engineio.async_drivers.' + mode)._async
+ asyncio_based = self._async['asyncio'] \
+ if 'asyncio' in self._async else False
+ if asyncio_based != self.is_asyncio_based():
+ continue # pragma: no cover
+ self.async_mode = mode
+ break
+ except ImportError:
+ pass
+ if self.async_mode is None:
+ raise ValueError('Invalid async_mode specified')
+ if self.is_asyncio_based() and \
+ ('asyncio' not in self._async or not
+ self._async['asyncio']): # pragma: no cover
+ raise ValueError('The selected async_mode is not asyncio '
+ 'compatible')
+ if not self.is_asyncio_based() and 'asyncio' in self._async and \
+ self._async['asyncio']: # pragma: no cover
+ raise ValueError('The selected async_mode requires asyncio and '
+ 'must use the AsyncServer class')
+ if transports is not None:
+ if isinstance(transports, str):
+ transports = [transports]
+ transports = [transport for transport in transports
+ if transport in self.valid_transports]
+ if not transports:
+ raise ValueError('No valid transports provided')
+ self.transports = transports or self.valid_transports
+ self.logger.info('Server initialized for %s.', self.async_mode)
+
+ def is_asyncio_based(self):
+ return False
+
+ def async_modes(self):
+ return ['eventlet', 'gevent_uwsgi', 'gevent', 'threading']
+
+ def on(self, event, handler=None):
+ """Register an event handler.
+
+ :param event: The event name. Can be ``'connect'``, ``'message'`` or
+ ``'disconnect'``.
+ :param handler: The function that should be invoked to handle the
+ event. When this parameter is not given, the method
+ acts as a decorator for the handler function.
+
+ Example usage::
+
+ # as a decorator:
+ @eio.on('connect')
+ def connect_handler(sid, environ):
+ print('Connection request')
+ if environ['REMOTE_ADDR'] in blacklisted:
+ return False # reject
+
+ # as a method:
+ def message_handler(sid, msg):
+ print('Received message: ', msg)
+ eio.send(sid, 'response')
+ eio.on('message', message_handler)
+
+ The handler function receives the ``sid`` (session ID) for the
+ client as first argument. The ``'connect'`` event handler receives the
+ WSGI environment as a second argument, and can return ``False`` to
+ reject the connection. The ``'message'`` handler receives the message
+ payload as a second argument. The ``'disconnect'`` handler does not
+ take a second argument.
+ """
+ if event not in self.event_names:
+ raise ValueError('Invalid event')
+
+ def set_handler(handler):
+ self.handlers[event] = handler
+ return handler
+
+ if handler is None:
+ return set_handler
+ set_handler(handler)
+
+ def transport(self, sid):
+ """Return the name of the transport used by the client.
+
+ The two possible values returned by this function are ``'polling'``
+ and ``'websocket'``.
+
+ :param sid: The session of the client.
+ """
+ return 'websocket' if self._get_socket(sid).upgraded else 'polling'
+
+ def create_queue(self, *args, **kwargs):
+ """Create a queue object using the appropriate async model.
+
+ This is a utility function that applications can use to create a queue
+ without having to worry about using the correct call for the selected
+ async mode.
+ """
+ return self._async['queue'](*args, **kwargs)
+
+ def get_queue_empty_exception(self):
+ """Return the queue empty exception for the appropriate async model.
+
+ This is a utility function that applications can use to work with a
+ queue without having to worry about using the correct call for the
+ selected async mode.
+ """
+ return self._async['queue_empty']
+
+ def create_event(self, *args, **kwargs):
+ """Create an event object using the appropriate async model.
+
+ This is a utility function that applications can use to create an
+ event without having to worry about using the correct call for the
+ selected async mode.
+ """
+ return self._async['event'](*args, **kwargs)
+
+ def generate_id(self):
+ """Generate a unique session id."""
+ id = base64.b64encode(
+ secrets.token_bytes(12) + self.sequence_number.to_bytes(3, 'big'))
+ self.sequence_number = (self.sequence_number + 1) & 0xffffff
+ return id.decode('utf-8').replace('/', '_').replace('+', '-')
+
+ def _generate_sid_cookie(self, sid, attributes):
+ """Generate the sid cookie."""
+ cookie = attributes.get('name', 'io') + '=' + sid
+ for attribute, value in attributes.items():
+ if attribute == 'name':
+ continue
+ if callable(value):
+ value = value()
+ if value is True:
+ cookie += '; ' + attribute
+ else:
+ cookie += '; ' + attribute + '=' + value
+ return cookie
+
+ def _upgrades(self, sid, transport):
+ """Return the list of possible upgrades for a client connection."""
+ if not self.allow_upgrades or self._get_socket(sid).upgraded or \
+ transport == 'websocket':
+ return []
+ if self._async['websocket'] is None: # pragma: no cover
+ self._log_error_once(
+ 'The WebSocket transport is not available, you must install a '
+ 'WebSocket server that is compatible with your async mode to '
+ 'enable it. See the documentation for details.',
+ 'no-websocket')
+ return []
+ return ['websocket']
+
+ def _get_socket(self, sid):
+ """Return the socket object for a given session."""
+ try:
+ s = self.sockets[sid]
+ except KeyError:
+ raise KeyError('Session not found')
+ if s.closed:
+ del self.sockets[sid]
+ raise KeyError('Session is disconnected')
+ return s
+
+ def _ok(self, packets=None, headers=None, jsonp_index=None):
+ """Generate a successful HTTP response."""
+ if packets is not None:
+ if headers is None:
+ headers = []
+ headers += [('Content-Type', 'text/plain; charset=UTF-8')]
+ return {'status': '200 OK',
+ 'headers': headers,
+ 'response': payload.Payload(packets=packets).encode(
+ jsonp_index=jsonp_index).encode('utf-8')}
+ else:
+ return {'status': '200 OK',
+ 'headers': [('Content-Type', 'text/plain')],
+ 'response': b'OK'}
+
+ def _bad_request(self, message=None):
+ """Generate a bad request HTTP error response."""
+ if message is None:
+ message = 'Bad Request'
+ message = packet.Packet.json.dumps(message)
+ return {'status': '400 BAD REQUEST',
+ 'headers': [('Content-Type', 'text/plain')],
+ 'response': message.encode('utf-8')}
+
+ def _method_not_found(self):
+ """Generate a method not found HTTP error response."""
+ return {'status': '405 METHOD NOT FOUND',
+ 'headers': [('Content-Type', 'text/plain')],
+ 'response': b'Method Not Found'}
+
+ def _unauthorized(self, message=None):
+ """Generate a unauthorized HTTP error response."""
+ if message is None:
+ message = 'Unauthorized'
+ message = packet.Packet.json.dumps(message)
+ return {'status': '401 UNAUTHORIZED',
+ 'headers': [('Content-Type', 'application/json')],
+ 'response': message.encode('utf-8')}
+
+ def _cors_allowed_origins(self, environ):
+ default_origins = []
+ if 'wsgi.url_scheme' in environ and 'HTTP_HOST' in environ:
+ default_origins.append('{scheme}://{host}'.format(
+ scheme=environ['wsgi.url_scheme'], host=environ['HTTP_HOST']))
+ if 'HTTP_X_FORWARDED_PROTO' in environ or \
+ 'HTTP_X_FORWARDED_HOST' in environ:
+ scheme = environ.get(
+ 'HTTP_X_FORWARDED_PROTO',
+ environ['wsgi.url_scheme']).split(',')[0].strip()
+ default_origins.append('{scheme}://{host}'.format(
+ scheme=scheme, host=environ.get(
+ 'HTTP_X_FORWARDED_HOST', environ['HTTP_HOST']).split(
+ ',')[0].strip()))
+ if self.cors_allowed_origins is None:
+ allowed_origins = default_origins
+ elif self.cors_allowed_origins == '*':
+ allowed_origins = None
+ elif isinstance(self.cors_allowed_origins, str):
+ allowed_origins = [self.cors_allowed_origins]
+ elif callable(self.cors_allowed_origins):
+ origin = environ.get('HTTP_ORIGIN')
+ allowed_origins = [origin] \
+ if self.cors_allowed_origins(origin) else []
+ else:
+ allowed_origins = self.cors_allowed_origins
+ return allowed_origins
+
+ def _cors_headers(self, environ):
+ """Return the cross-origin-resource-sharing headers."""
+ if self.cors_allowed_origins == []:
+ # special case, CORS handling is completely disabled
+ return []
+ headers = []
+ allowed_origins = self._cors_allowed_origins(environ)
+ if 'HTTP_ORIGIN' in environ and \
+ (allowed_origins is None or environ['HTTP_ORIGIN'] in
+ allowed_origins):
+ headers = [('Access-Control-Allow-Origin', environ['HTTP_ORIGIN'])]
+ if environ['REQUEST_METHOD'] == 'OPTIONS':
+ headers += [('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')]
+ if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ:
+ headers += [('Access-Control-Allow-Headers',
+ environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])]
+ if self.cors_credentials:
+ headers += [('Access-Control-Allow-Credentials', 'true')]
+ return headers
+
+ def _gzip(self, response):
+ """Apply gzip compression to a response."""
+ bytesio = io.BytesIO()
+ with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:
+ gz.write(response)
+ return bytesio.getvalue()
+
+ def _deflate(self, response):
+ """Apply deflate compression to a response."""
+ return zlib.compress(response)
+
+ def _log_error_once(self, message, message_key):
+ """Log message with logging.ERROR level the first time, then log
+ with given level."""
+ if message_key not in self.log_message_keys:
+ self.logger.error(message + ' (further occurrences of this error '
+ 'will be logged with level INFO)')
+ self.log_message_keys.add(message_key)
+ else:
+ self.logger.info(message)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_socket.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_socket.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d42bfec54feaa571e0735e7e016a3ef59befb4b
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/base_socket.py
@@ -0,0 +1,15 @@
+
+class BaseSocket:
+ upgrade_protocols = ['websocket']
+
+ def __init__(self, server, sid):
+ self.server = server
+ self.sid = sid
+ self.queue = self.server.create_queue()
+ self.last_ping = None
+ self.connected = False
+ self.upgrading = False
+ self.upgraded = False
+ self.closing = False
+ self.closed = False
+ self.session = {}
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..8775179dc3cbf7a5e5876500b9afe53a6e6b784e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/client.py
@@ -0,0 +1,605 @@
+from base64 import b64encode
+from engineio.json import JSONDecodeError
+import logging
+import queue
+import ssl
+import threading
+import time
+import urllib
+
+try:
+ import requests
+except ImportError: # pragma: no cover
+ requests = None
+try:
+ import websocket
+except ImportError: # pragma: no cover
+ websocket = None
+from . import base_client
+from . import exceptions
+from . import packet
+from . import payload
+
+default_logger = logging.getLogger('engineio.client')
+
+
+class Client(base_client.BaseClient):
+ """An Engine.IO client.
+
+ This class implements a fully compliant Engine.IO web client with support
+ for websocket and long-polling transports.
+
+ :param logger: To enable logging set to ``True`` or pass a logger object to
+ use. To disable logging set to ``False``. The default is
+ ``False``. Note that fatal errors are logged even when
+ ``logger`` is ``False``.
+ :param json: An alternative json module to use for encoding and decoding
+ packets. Custom json modules must have ``dumps`` and ``loads``
+ functions that are compatible with the standard library
+ versions.
+ :param request_timeout: A timeout in seconds for requests. The default is
+ 5 seconds.
+ :param http_session: an initialized ``requests.Session`` object to be used
+ when sending requests to the server. Use it if you
+ need to add special client options such as proxy
+ servers, SSL certificates, custom CA bundle, etc.
+ :param ssl_verify: ``True`` to verify SSL certificates, or ``False`` to
+ skip SSL certificate verification, allowing
+ connections to servers with self signed certificates.
+ The default is ``True``.
+ :param handle_sigint: Set to ``True`` to automatically handle disconnection
+ when the process is interrupted, or to ``False`` to
+ leave interrupt handling to the calling application.
+ Interrupt handling can only be enabled when the
+ client instance is created in the main thread.
+ :param websocket_extra_options: Dictionary containing additional keyword
+ arguments passed to
+ ``websocket.create_connection()``.
+ """
+ def connect(self, url, headers=None, transports=None,
+ engineio_path='engine.io'):
+ """Connect to an Engine.IO server.
+
+ :param url: The URL of the Engine.IO server. It can include custom
+ query string parameters if required by the server.
+ :param headers: A dictionary with custom headers to send with the
+ connection request.
+ :param transports: The list of allowed transports. Valid transports
+ are ``'polling'`` and ``'websocket'``. If not
+ given, the polling transport is connected first,
+ then an upgrade to websocket is attempted.
+ :param engineio_path: The endpoint where the Engine.IO server is
+ installed. The default value is appropriate for
+ most cases.
+
+ Example usage::
+
+ eio = engineio.Client()
+ eio.connect('http://localhost:5000')
+ """
+ if self.state != 'disconnected':
+ raise ValueError('Client is not in a disconnected state')
+ valid_transports = ['polling', 'websocket']
+ if transports is not None:
+ if isinstance(transports, str):
+ transports = [transports]
+ transports = [transport for transport in transports
+ if transport in valid_transports]
+ if not transports:
+ raise ValueError('No valid transports provided')
+ self.transports = transports or valid_transports
+ self.queue = self.create_queue()
+ return getattr(self, '_connect_' + self.transports[0])(
+ url, headers or {}, engineio_path)
+
+ def wait(self):
+ """Wait until the connection with the server ends.
+
+ Client applications can use this function to block the main thread
+ during the life of the connection.
+ """
+ if self.read_loop_task:
+ self.read_loop_task.join()
+
+ def send(self, data):
+ """Send a message to the server.
+
+ :param data: The data to send to the server. Data can be of type
+ ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
+ or ``dict``, the data will be serialized as JSON.
+ """
+ self._send_packet(packet.Packet(packet.MESSAGE, data=data))
+
+ def disconnect(self, abort=False):
+ """Disconnect from the server.
+
+ :param abort: If set to ``True``, do not wait for background tasks
+ associated with the connection to end.
+ """
+ if self.state == 'connected':
+ self._send_packet(packet.Packet(packet.CLOSE))
+ self.queue.put(None)
+ self.state = 'disconnecting'
+ self._trigger_event('disconnect', run_async=False)
+ if self.current_transport == 'websocket':
+ self.ws.close()
+ if not abort:
+ self.read_loop_task.join()
+ self.state = 'disconnected'
+ try:
+ base_client.connected_clients.remove(self)
+ except ValueError: # pragma: no cover
+ pass
+ self._reset()
+
+ def start_background_task(self, target, *args, **kwargs):
+ """Start a background task.
+
+ This is a utility function that applications can use to start a
+ background task.
+
+ :param target: the target function to execute.
+ :param args: arguments to pass to the function.
+ :param kwargs: keyword arguments to pass to the function.
+
+ This function returns an object that represents the background task,
+ on which the ``join()`` method can be invoked to wait for the task to
+ complete.
+ """
+ th = threading.Thread(target=target, args=args, kwargs=kwargs,
+ daemon=True)
+ th.start()
+ return th
+
+ def sleep(self, seconds=0):
+ """Sleep for the requested amount of time."""
+ return time.sleep(seconds)
+
+ def create_queue(self, *args, **kwargs):
+ """Create a queue object."""
+ q = queue.Queue(*args, **kwargs)
+ q.Empty = queue.Empty
+ return q
+
+ def create_event(self, *args, **kwargs):
+ """Create an event object."""
+ return threading.Event(*args, **kwargs)
+
+ def _connect_polling(self, url, headers, engineio_path):
+ """Establish a long-polling connection to the Engine.IO server."""
+ if requests is None: # pragma: no cover
+ # not installed
+ self.logger.error('requests package is not installed -- cannot '
+ 'send HTTP requests!')
+ return
+ self.base_url = self._get_engineio_url(url, engineio_path, 'polling')
+ self.logger.info('Attempting polling connection to ' + self.base_url)
+ r = self._send_request(
+ 'GET', self.base_url + self._get_url_timestamp(), headers=headers,
+ timeout=self.request_timeout)
+ if r is None or isinstance(r, str):
+ self._reset()
+ raise exceptions.ConnectionError(
+ r or 'Connection refused by the server')
+ if r.status_code < 200 or r.status_code >= 300:
+ self._reset()
+ try:
+ arg = r.json()
+ except JSONDecodeError:
+ arg = None
+ raise exceptions.ConnectionError(
+ 'Unexpected status code {} in server response'.format(
+ r.status_code), arg)
+ try:
+ p = payload.Payload(encoded_payload=r.content.decode('utf-8'))
+ except ValueError:
+ raise exceptions.ConnectionError(
+ 'Unexpected response from server') from None
+ open_packet = p.packets[0]
+ if open_packet.packet_type != packet.OPEN:
+ raise exceptions.ConnectionError(
+ 'OPEN packet not returned by server')
+ self.logger.info(
+ 'Polling connection accepted with ' + str(open_packet.data))
+ self.sid = open_packet.data['sid']
+ self.upgrades = open_packet.data['upgrades']
+ self.ping_interval = int(open_packet.data['pingInterval']) / 1000.0
+ self.ping_timeout = int(open_packet.data['pingTimeout']) / 1000.0
+ self.current_transport = 'polling'
+ self.base_url += '&sid=' + self.sid
+
+ self.state = 'connected'
+ base_client.connected_clients.append(self)
+ self._trigger_event('connect', run_async=False)
+
+ for pkt in p.packets[1:]:
+ self._receive_packet(pkt)
+
+ if 'websocket' in self.upgrades and 'websocket' in self.transports:
+ # attempt to upgrade to websocket
+ if self._connect_websocket(url, headers, engineio_path):
+ # upgrade to websocket succeeded, we're done here
+ return
+
+ # start background tasks associated with this client
+ self.write_loop_task = self.start_background_task(self._write_loop)
+ self.read_loop_task = self.start_background_task(
+ self._read_loop_polling)
+
+ def _connect_websocket(self, url, headers, engineio_path):
+ """Establish or upgrade to a WebSocket connection with the server."""
+ if websocket is None: # pragma: no cover
+ # not installed
+ self.logger.error('websocket-client package not installed, only '
+ 'polling transport is available')
+ return False
+ websocket_url = self._get_engineio_url(url, engineio_path, 'websocket')
+ if self.sid:
+ self.logger.info(
+ 'Attempting WebSocket upgrade to ' + websocket_url)
+ upgrade = True
+ websocket_url += '&sid=' + self.sid
+ else:
+ upgrade = False
+ self.base_url = websocket_url
+ self.logger.info(
+ 'Attempting WebSocket connection to ' + websocket_url)
+
+ # get cookies and other settings from the long-polling connection
+ # so that they are preserved when connecting to the WebSocket route
+ cookies = None
+ extra_options = {}
+ if self.http:
+ # cookies
+ cookies = '; '.join(["{}={}".format(cookie.name, cookie.value)
+ for cookie in self.http.cookies])
+ for header, value in headers.items():
+ if header.lower() == 'cookie':
+ if cookies:
+ cookies += '; '
+ cookies += value
+ del headers[header]
+ break
+
+ # auth
+ if 'Authorization' not in headers and self.http.auth is not None:
+ if not isinstance(self.http.auth, tuple): # pragma: no cover
+ raise ValueError('Only basic authentication is supported')
+ basic_auth = '{}:{}'.format(
+ self.http.auth[0], self.http.auth[1]).encode('utf-8')
+ basic_auth = b64encode(basic_auth).decode('utf-8')
+ headers['Authorization'] = 'Basic ' + basic_auth
+
+ # cert
+ # this can be given as ('certfile', 'keyfile') or just 'certfile'
+ if isinstance(self.http.cert, tuple):
+ extra_options['sslopt'] = {
+ 'certfile': self.http.cert[0],
+ 'keyfile': self.http.cert[1]}
+ elif self.http.cert:
+ extra_options['sslopt'] = {'certfile': self.http.cert}
+
+ # proxies
+ if self.http.proxies:
+ proxy_url = None
+ if websocket_url.startswith('ws://'):
+ proxy_url = self.http.proxies.get(
+ 'ws', self.http.proxies.get('http'))
+ else: # wss://
+ proxy_url = self.http.proxies.get(
+ 'wss', self.http.proxies.get('https'))
+ if proxy_url:
+ parsed_url = urllib.parse.urlparse(
+ proxy_url if '://' in proxy_url
+ else 'scheme://' + proxy_url)
+ extra_options['http_proxy_host'] = parsed_url.hostname
+ extra_options['http_proxy_port'] = parsed_url.port
+ extra_options['http_proxy_auth'] = (
+ (parsed_url.username, parsed_url.password)
+ if parsed_url.username or parsed_url.password
+ else None)
+
+ # verify
+ if isinstance(self.http.verify, str):
+ if 'sslopt' in extra_options:
+ extra_options['sslopt']['ca_certs'] = self.http.verify
+ else:
+ extra_options['sslopt'] = {'ca_certs': self.http.verify}
+ elif not self.http.verify:
+ self.ssl_verify = False
+
+ if not self.ssl_verify:
+ if 'sslopt' in extra_options:
+ extra_options['sslopt'].update({"cert_reqs": ssl.CERT_NONE})
+ else:
+ extra_options['sslopt'] = {"cert_reqs": ssl.CERT_NONE}
+
+ # combine internally generated options with the ones supplied by the
+ # caller. The caller's options take precedence.
+ headers.update(self.websocket_extra_options.pop('header', {}))
+ extra_options['header'] = headers
+ extra_options['cookie'] = cookies
+ extra_options['enable_multithread'] = True
+ extra_options['timeout'] = self.request_timeout
+ extra_options.update(self.websocket_extra_options)
+ try:
+ ws = websocket.create_connection(
+ websocket_url + self._get_url_timestamp(), **extra_options)
+ except (ConnectionError, IOError, websocket.WebSocketException):
+ if upgrade:
+ self.logger.warning(
+ 'WebSocket upgrade failed: connection error')
+ return False
+ else:
+ raise exceptions.ConnectionError('Connection error')
+ if upgrade:
+ p = packet.Packet(packet.PING, data='probe').encode()
+ try:
+ ws.send(p)
+ except Exception as e: # pragma: no cover
+ self.logger.warning(
+ 'WebSocket upgrade failed: unexpected send exception: %s',
+ str(e))
+ return False
+ try:
+ p = ws.recv()
+ except Exception as e: # pragma: no cover
+ self.logger.warning(
+ 'WebSocket upgrade failed: unexpected recv exception: %s',
+ str(e))
+ return False
+ pkt = packet.Packet(encoded_packet=p)
+ if pkt.packet_type != packet.PONG or pkt.data != 'probe':
+ self.logger.warning(
+ 'WebSocket upgrade failed: no PONG packet')
+ return False
+ p = packet.Packet(packet.UPGRADE).encode()
+ try:
+ ws.send(p)
+ except Exception as e: # pragma: no cover
+ self.logger.warning(
+ 'WebSocket upgrade failed: unexpected send exception: %s',
+ str(e))
+ return False
+ self.current_transport = 'websocket'
+ self.logger.info('WebSocket upgrade was successful')
+ else:
+ try:
+ p = ws.recv()
+ except Exception as e: # pragma: no cover
+ raise exceptions.ConnectionError(
+ 'Unexpected recv exception: ' + str(e))
+ open_packet = packet.Packet(encoded_packet=p)
+ if open_packet.packet_type != packet.OPEN:
+ raise exceptions.ConnectionError('no OPEN packet')
+ self.logger.info(
+ 'WebSocket connection accepted with ' + str(open_packet.data))
+ self.sid = open_packet.data['sid']
+ self.upgrades = open_packet.data['upgrades']
+ self.ping_interval = int(open_packet.data['pingInterval']) / 1000.0
+ self.ping_timeout = int(open_packet.data['pingTimeout']) / 1000.0
+ self.current_transport = 'websocket'
+
+ self.state = 'connected'
+ base_client.connected_clients.append(self)
+ self._trigger_event('connect', run_async=False)
+ self.ws = ws
+ self.ws.settimeout(self.ping_interval + self.ping_timeout)
+
+ # start background tasks associated with this client
+ self.write_loop_task = self.start_background_task(self._write_loop)
+ self.read_loop_task = self.start_background_task(
+ self._read_loop_websocket)
+ return True
+
+ def _receive_packet(self, pkt):
+ """Handle incoming packets from the server."""
+ packet_name = packet.packet_names[pkt.packet_type] \
+ if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN'
+ self.logger.info(
+ 'Received packet %s data %s', packet_name,
+ pkt.data if not isinstance(pkt.data, bytes) else '')
+ if pkt.packet_type == packet.MESSAGE:
+ self._trigger_event('message', pkt.data, run_async=True)
+ elif pkt.packet_type == packet.PING:
+ self._send_packet(packet.Packet(packet.PONG, pkt.data))
+ elif pkt.packet_type == packet.CLOSE:
+ self.disconnect(abort=True)
+ elif pkt.packet_type == packet.NOOP:
+ pass
+ else:
+ self.logger.error('Received unexpected packet of type %s',
+ pkt.packet_type)
+
+ def _send_packet(self, pkt):
+ """Queue a packet to be sent to the server."""
+ if self.state != 'connected':
+ return
+ self.queue.put(pkt)
+ self.logger.info(
+ 'Sending packet %s data %s',
+ packet.packet_names[pkt.packet_type],
+ pkt.data if not isinstance(pkt.data, bytes) else '')
+
+ def _send_request(
+ self, method, url, headers=None, body=None,
+ timeout=None): # pragma: no cover
+ if self.http is None:
+ self.http = requests.Session()
+ if not self.ssl_verify:
+ self.http.verify = False
+ try:
+ return self.http.request(method, url, headers=headers, data=body,
+ timeout=timeout)
+ except requests.exceptions.RequestException as exc:
+ self.logger.info('HTTP %s request to %s failed with error %s.',
+ method, url, exc)
+ return str(exc)
+
+ def _trigger_event(self, event, *args, **kwargs):
+ """Invoke an event handler."""
+ run_async = kwargs.pop('run_async', False)
+ if event in self.handlers:
+ if run_async:
+ return self.start_background_task(self.handlers[event], *args)
+ else:
+ try:
+ return self.handlers[event](*args)
+ except:
+ self.logger.exception(event + ' handler error')
+
+ def _read_loop_polling(self):
+ """Read packets by polling the Engine.IO server."""
+ while self.state == 'connected' and self.write_loop_task:
+ self.logger.info(
+ 'Sending polling GET request to ' + self.base_url)
+ r = self._send_request(
+ 'GET', self.base_url + self._get_url_timestamp(),
+ timeout=max(self.ping_interval, self.ping_timeout) + 5)
+ if r is None or isinstance(r, str):
+ self.logger.warning(
+ r or 'Connection refused by the server, aborting')
+ self.queue.put(None)
+ break
+ if r.status_code < 200 or r.status_code >= 300:
+ self.logger.warning('Unexpected status code %s in server '
+ 'response, aborting', r.status_code)
+ self.queue.put(None)
+ break
+ try:
+ p = payload.Payload(encoded_payload=r.content.decode('utf-8'))
+ except ValueError:
+ self.logger.warning(
+ 'Unexpected packet from server, aborting')
+ self.queue.put(None)
+ break
+ for pkt in p.packets:
+ self._receive_packet(pkt)
+
+ if self.write_loop_task: # pragma: no branch
+ self.logger.info('Waiting for write loop task to end')
+ self.write_loop_task.join()
+ if self.state == 'connected':
+ self._trigger_event('disconnect', run_async=False)
+ try:
+ base_client.connected_clients.remove(self)
+ except ValueError: # pragma: no cover
+ pass
+ self._reset()
+ self.logger.info('Exiting read loop task')
+
+ def _read_loop_websocket(self):
+ """Read packets from the Engine.IO WebSocket connection."""
+ while self.state == 'connected':
+ p = None
+ try:
+ p = self.ws.recv()
+ if len(p) == 0: # pragma: no cover
+ # websocket client can return an empty string after close
+ raise websocket.WebSocketConnectionClosedException()
+ except websocket.WebSocketTimeoutException:
+ self.logger.warning(
+ 'Server has stopped communicating, aborting')
+ self.queue.put(None)
+ break
+ except websocket.WebSocketConnectionClosedException:
+ self.logger.warning(
+ 'WebSocket connection was closed, aborting')
+ self.queue.put(None)
+ break
+ except Exception as e: # pragma: no cover
+ if type(e) is OSError and e.errno == 9:
+ self.logger.info(
+ 'WebSocket connection is closing, aborting',
+ str(e))
+ else:
+ self.logger.info(
+ 'Unexpected error receiving packet: "%s", aborting',
+ str(e))
+ self.queue.put(None)
+ break
+ try:
+ pkt = packet.Packet(encoded_packet=p)
+ except Exception as e: # pragma: no cover
+ self.logger.info(
+ 'Unexpected error decoding packet: "%s", aborting', str(e))
+ self.queue.put(None)
+ break
+ self._receive_packet(pkt)
+
+ if self.write_loop_task: # pragma: no branch
+ self.logger.info('Waiting for write loop task to end')
+ self.write_loop_task.join()
+ if self.state == 'connected':
+ self._trigger_event('disconnect', run_async=False)
+ try:
+ base_client.connected_clients.remove(self)
+ except ValueError: # pragma: no cover
+ pass
+ self._reset()
+ self.logger.info('Exiting read loop task')
+
+ def _write_loop(self):
+ """This background task sends packages to the server as they are
+ pushed to the send queue.
+ """
+ while self.state == 'connected':
+ # to simplify the timeout handling, use the maximum of the
+ # ping interval and ping timeout as timeout, with an extra 5
+ # seconds grace period
+ timeout = max(self.ping_interval, self.ping_timeout) + 5
+ packets = None
+ try:
+ packets = [self.queue.get(timeout=timeout)]
+ except self.queue.Empty:
+ self.logger.error('packet queue is empty, aborting')
+ break
+ if packets == [None]:
+ self.queue.task_done()
+ packets = []
+ else:
+ while True:
+ try:
+ packets.append(self.queue.get(block=False))
+ except self.queue.Empty:
+ break
+ if packets[-1] is None:
+ packets = packets[:-1]
+ self.queue.task_done()
+ break
+ if not packets:
+ # empty packet list returned -> connection closed
+ break
+ if self.current_transport == 'polling':
+ p = payload.Payload(packets=packets)
+ r = self._send_request(
+ 'POST', self.base_url, body=p.encode(),
+ headers={'Content-Type': 'text/plain'},
+ timeout=self.request_timeout)
+ for pkt in packets:
+ self.queue.task_done()
+ if r is None or isinstance(r, str):
+ self.logger.warning(
+ r or 'Connection refused by the server, aborting')
+ break
+ if r.status_code < 200 or r.status_code >= 300:
+ self.logger.warning('Unexpected status code %s in server '
+ 'response, aborting', r.status_code)
+ self.write_loop_task = None
+ break
+ else:
+ # websocket
+ try:
+ for pkt in packets:
+ encoded_packet = pkt.encode()
+ if pkt.binary:
+ self.ws.send_binary(encoded_packet)
+ else:
+ self.ws.send(encoded_packet)
+ self.queue.task_done()
+ except (websocket.WebSocketConnectionClosedException,
+ BrokenPipeError, OSError):
+ self.logger.warning(
+ 'WebSocket connection was closed, aborting')
+ break
+ self.logger.info('Exiting write loop task')
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/exceptions.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb0b3e057cb76d0a2265151d31ddfe4c68aa24b5
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/exceptions.py
@@ -0,0 +1,22 @@
+class EngineIOError(Exception):
+ pass
+
+
+class ContentTooLongError(EngineIOError):
+ pass
+
+
+class UnknownPacketError(EngineIOError):
+ pass
+
+
+class QueueEmpty(EngineIOError):
+ pass
+
+
+class SocketIsClosedError(EngineIOError):
+ pass
+
+
+class ConnectionError(EngineIOError):
+ pass
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/json.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/json.py
new file mode 100644
index 0000000000000000000000000000000000000000..b612556834376c16a3b3f0566274c9ac9e960a10
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/json.py
@@ -0,0 +1,16 @@
+"""JSON-compatible module with sane defaults."""
+
+from json import * # noqa: F401, F403
+from json import loads as original_loads
+
+
+def _safe_int(s):
+ if len(s) > 100:
+ raise ValueError('Integer is too large')
+ return int(s)
+
+
+def loads(*args, **kwargs):
+ if 'parse_int' not in kwargs: # pragma: no cover
+ kwargs['parse_int'] = _safe_int
+ return original_loads(*args, **kwargs)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/middleware.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..e198737f5cd4a2119205ea761821d2cad1b408d2
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/middleware.py
@@ -0,0 +1,86 @@
+import os
+from engineio.static_files import get_static_file
+
+
+class WSGIApp(object):
+ """WSGI application middleware for Engine.IO.
+
+ This middleware dispatches traffic to an Engine.IO application. It can
+ also serve a list of static files to the client, or forward unrelated
+ HTTP traffic to another WSGI application.
+
+ :param engineio_app: The Engine.IO server. Must be an instance of the
+ ``engineio.Server`` class.
+ :param wsgi_app: The WSGI app that receives all other traffic.
+ :param static_files: A dictionary with static file mapping rules. See the
+ documentation for details on this argument.
+ :param engineio_path: The endpoint where the Engine.IO application should
+ be installed. The default value is appropriate for
+ most cases.
+
+ Example usage::
+
+ import engineio
+ import eventlet
+
+ eio = engineio.Server()
+ app = engineio.WSGIApp(eio, static_files={
+ '/': {'content_type': 'text/html', 'filename': 'index.html'},
+ '/index.html': {'content_type': 'text/html',
+ 'filename': 'index.html'},
+ })
+ eventlet.wsgi.server(eventlet.listen(('', 8000)), app)
+ """
+ def __init__(self, engineio_app, wsgi_app=None, static_files=None,
+ engineio_path='engine.io'):
+ self.engineio_app = engineio_app
+ self.wsgi_app = wsgi_app
+ self.engineio_path = engineio_path
+ if not self.engineio_path.startswith('/'):
+ self.engineio_path = '/' + self.engineio_path
+ if not self.engineio_path.endswith('/'):
+ self.engineio_path += '/'
+ self.static_files = static_files or {}
+
+ def __call__(self, environ, start_response):
+ if 'gunicorn.socket' in environ:
+ # gunicorn saves the socket under environ['gunicorn.socket'], while
+ # eventlet saves it under environ['eventlet.input']. Eventlet also
+ # stores the socket inside a wrapper class, while gunicon writes it
+ # directly into the environment. To give eventlet's WebSocket
+ # module access to this socket when running under gunicorn, here we
+ # copy the socket to the eventlet format.
+ class Input(object):
+ def __init__(self, socket):
+ self.socket = socket
+
+ def get_socket(self):
+ return self.socket
+
+ environ['eventlet.input'] = Input(environ['gunicorn.socket'])
+ path = environ['PATH_INFO']
+ if path is not None and path.startswith(self.engineio_path):
+ return self.engineio_app.handle_request(environ, start_response)
+ else:
+ static_file = get_static_file(path, self.static_files) \
+ if self.static_files else None
+ if static_file and os.path.exists(static_file['filename']):
+ start_response(
+ '200 OK',
+ [('Content-Type', static_file['content_type'])])
+ with open(static_file['filename'], 'rb') as f:
+ return [f.read()]
+ elif self.wsgi_app is not None:
+ return self.wsgi_app(environ, start_response)
+ return self.not_found(start_response)
+
+ def not_found(self, start_response):
+ start_response("404 Not Found", [('Content-Type', 'text/plain')])
+ return [b'Not Found']
+
+
+class Middleware(WSGIApp):
+ """This class has been renamed to ``WSGIApp`` and is now deprecated."""
+ def __init__(self, engineio_app, wsgi_app=None,
+ engineio_path='engine.io'):
+ super().__init__(engineio_app, wsgi_app, engineio_path=engineio_path)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/packet.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/packet.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e8135ccf6ae5a66de26cf4e6cae3fbcf03fe3b6
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/packet.py
@@ -0,0 +1,82 @@
+import base64
+from engineio import json as _json
+
+(OPEN, CLOSE, PING, PONG, MESSAGE, UPGRADE, NOOP) = (0, 1, 2, 3, 4, 5, 6)
+packet_names = ['OPEN', 'CLOSE', 'PING', 'PONG', 'MESSAGE', 'UPGRADE', 'NOOP']
+
+binary_types = (bytes, bytearray)
+
+
+class Packet(object):
+ """Engine.IO packet."""
+
+ json = _json
+
+ def __init__(self, packet_type=NOOP, data=None, encoded_packet=None):
+ self.packet_type = packet_type
+ self.data = data
+ self.encode_cache = None
+ if isinstance(data, str):
+ self.binary = False
+ elif isinstance(data, binary_types):
+ self.binary = True
+ else:
+ self.binary = False
+ if self.binary and self.packet_type != MESSAGE:
+ raise ValueError('Binary packets can only be of type MESSAGE')
+ if encoded_packet is not None:
+ self.decode(encoded_packet)
+
+ def encode(self, b64=False):
+ """Encode the packet for transmission.
+
+ Note: as a performance optimization, subsequent calls to this method
+ will return a cached encoded packet, even if the data has changed.
+ """
+ if self.encode_cache:
+ return self.encode_cache
+ if self.binary:
+ if b64:
+ encoded_packet = 'b' + base64.b64encode(self.data).decode(
+ 'utf-8')
+ else:
+ encoded_packet = self.data
+ else:
+ encoded_packet = str(self.packet_type)
+ if isinstance(self.data, str):
+ encoded_packet += self.data
+ elif isinstance(self.data, dict) or isinstance(self.data, list):
+ encoded_packet += self.json.dumps(self.data,
+ separators=(',', ':'))
+ elif self.data is not None:
+ encoded_packet += str(self.data)
+ self.encode_cache = encoded_packet
+ return encoded_packet
+
+ def decode(self, encoded_packet):
+ """Decode a transmitted package."""
+ self.binary = isinstance(encoded_packet, binary_types)
+ if not self.binary and len(encoded_packet) == 0:
+ raise ValueError('Invalid empty packet received')
+ b64 = not self.binary and encoded_packet[0] == 'b'
+ if b64:
+ self.binary = True
+ self.packet_type = MESSAGE
+ self.data = base64.b64decode(encoded_packet[1:])
+ else:
+ if self.binary and not isinstance(encoded_packet, bytes):
+ encoded_packet = bytes(encoded_packet)
+ if self.binary:
+ self.packet_type = MESSAGE
+ self.data = encoded_packet
+ else:
+ self.packet_type = int(encoded_packet[0])
+ try:
+ self.data = self.json.loads(encoded_packet[1:])
+ if isinstance(self.data, int):
+ # do not allow integer payloads, see
+ # github.com/miguelgrinberg/python-engineio/issues/75
+ # for background on this decision
+ raise ValueError
+ except ValueError:
+ self.data = encoded_packet[1:]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/payload.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/payload.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0e9e343db4fe53139ec126b860f87fc76ad8564
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/payload.py
@@ -0,0 +1,46 @@
+import urllib
+
+from . import packet
+
+
+class Payload(object):
+ """Engine.IO payload."""
+ max_decode_packets = 16
+
+ def __init__(self, packets=None, encoded_payload=None):
+ self.packets = packets or []
+ if encoded_payload is not None:
+ self.decode(encoded_payload)
+
+ def encode(self, jsonp_index=None):
+ """Encode the payload for transmission."""
+ encoded_payload = ''
+ for pkt in self.packets:
+ if encoded_payload:
+ encoded_payload += '\x1e'
+ encoded_payload += pkt.encode(b64=True)
+ if jsonp_index is not None:
+ encoded_payload = '___eio[' + \
+ str(jsonp_index) + \
+ ']("' + \
+ encoded_payload.replace('"', '\\"') + \
+ '");'
+ return encoded_payload
+
+ def decode(self, encoded_payload):
+ """Decode a transmitted payload."""
+ self.packets = []
+
+ if len(encoded_payload) == 0:
+ return
+
+ # JSONP POST payload starts with 'd='
+ if encoded_payload.startswith('d='):
+ encoded_payload = urllib.parse.parse_qs(
+ encoded_payload)['d'][0]
+
+ encoded_packets = encoded_payload.split('\x1e')
+ if len(encoded_packets) > self.max_decode_packets:
+ raise ValueError('Too many packets in payload')
+ self.packets = [packet.Packet(encoded_packet=encoded_packet)
+ for encoded_packet in encoded_packets]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/server.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..3926b226a54bc675019b109cb0ead6c6664f5922
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/server.py
@@ -0,0 +1,479 @@
+import logging
+import urllib
+
+from . import base_server
+from . import exceptions
+from . import packet
+from . import socket
+
+default_logger = logging.getLogger('engineio.server')
+
+
+class Server(base_server.BaseServer):
+ """An Engine.IO server.
+
+ This class implements a fully compliant Engine.IO web server with support
+ for websocket and long-polling transports.
+
+ :param async_mode: The asynchronous model to use. See the Deployment
+ section in the documentation for a description of the
+ available options. Valid async modes are "threading",
+ "eventlet", "gevent" and "gevent_uwsgi". If this
+ argument is not given, "eventlet" is tried first, then
+ "gevent_uwsgi", then "gevent", and finally "threading".
+ The first async mode that has all its dependencies
+ installed is the one that is chosen.
+ :param ping_interval: The interval in seconds at which the server pings
+ the client. The default is 25 seconds. For advanced
+ control, a two element tuple can be given, where
+ the first number is the ping interval and the second
+ is a grace period added by the server.
+ :param ping_timeout: The time in seconds that the client waits for the
+ server to respond before disconnecting. The default
+ is 20 seconds.
+ :param max_http_buffer_size: The maximum size that is accepted for incoming
+ messages. The default is 1,000,000 bytes. In
+ spite of its name, the value set in this
+ argument is enforced for HTTP long-polling and
+ WebSocket connections.
+ :param allow_upgrades: Whether to allow transport upgrades or not. The
+ default is ``True``.
+ :param http_compression: Whether to compress packages when using the
+ polling transport. The default is ``True``.
+ :param compression_threshold: Only compress messages when their byte size
+ is greater than this value. The default is
+ 1024 bytes.
+ :param cookie: If set to a string, it is the name of the HTTP cookie the
+ server sends back tot he client containing the client
+ session id. If set to a dictionary, the ``'name'`` key
+ contains the cookie name and other keys define cookie
+ attributes, where the value of each attribute can be a
+ string, a callable with no arguments, or a boolean. If set
+ to ``None`` (the default), a cookie is not sent to the
+ client.
+ :param cors_allowed_origins: Origin or list of origins that are allowed to
+ connect to this server. Only the same origin
+ is allowed by default. Set this argument to
+ ``'*'`` to allow all origins, or to ``[]`` to
+ disable CORS handling.
+ :param cors_credentials: Whether credentials (cookies, authentication) are
+ allowed in requests to this server. The default
+ is ``True``.
+ :param logger: To enable logging set to ``True`` or pass a logger object to
+ use. To disable logging set to ``False``. The default is
+ ``False``. Note that fatal errors are logged even when
+ ``logger`` is ``False``.
+ :param json: An alternative json module to use for encoding and decoding
+ packets. Custom json modules must have ``dumps`` and ``loads``
+ functions that are compatible with the standard library
+ versions.
+ :param async_handlers: If set to ``True``, run message event handlers in
+ non-blocking threads. To run handlers synchronously,
+ set to ``False``. The default is ``True``.
+ :param monitor_clients: If set to ``True``, a background task will ensure
+ inactive clients are closed. Set to ``False`` to
+ disable the monitoring task (not recommended). The
+ default is ``True``.
+ :param transports: The list of allowed transports. Valid transports
+ are ``'polling'`` and ``'websocket'``. Defaults to
+ ``['polling', 'websocket']``.
+ :param kwargs: Reserved for future extensions, any additional parameters
+ given as keyword arguments will be silently ignored.
+ """
+ def send(self, sid, data):
+ """Send a message to a client.
+
+ :param sid: The session id of the recipient client.
+ :param data: The data to send to the client. Data can be of type
+ ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
+ or ``dict``, the data will be serialized as JSON.
+ """
+ self.send_packet(sid, packet.Packet(packet.MESSAGE, data=data))
+
+ def send_packet(self, sid, pkt):
+ """Send a raw packet to a client.
+
+ :param sid: The session id of the recipient client.
+ :param pkt: The packet to send to the client.
+ """
+ try:
+ socket = self._get_socket(sid)
+ except KeyError:
+ # the socket is not available
+ self.logger.warning('Cannot send to sid %s', sid)
+ return
+ socket.send(pkt)
+
+ def get_session(self, sid):
+ """Return the user session for a client.
+
+ :param sid: The session id of the client.
+
+ The return value is a dictionary. Modifications made to this
+ dictionary are not guaranteed to be preserved unless
+ ``save_session()`` is called, or when the ``session`` context manager
+ is used.
+ """
+ socket = self._get_socket(sid)
+ return socket.session
+
+ def save_session(self, sid, session):
+ """Store the user session for a client.
+
+ :param sid: The session id of the client.
+ :param session: The session dictionary.
+ """
+ socket = self._get_socket(sid)
+ socket.session = session
+
+ def session(self, sid):
+ """Return the user session for a client with context manager syntax.
+
+ :param sid: The session id of the client.
+
+ This is a context manager that returns the user session dictionary for
+ the client. Any changes that are made to this dictionary inside the
+ context manager block are saved back to the session. Example usage::
+
+ @eio.on('connect')
+ def on_connect(sid, environ):
+ username = authenticate_user(environ)
+ if not username:
+ return False
+ with eio.session(sid) as session:
+ session['username'] = username
+
+ @eio.on('message')
+ def on_message(sid, msg):
+ with eio.session(sid) as session:
+ print('received message from ', session['username'])
+ """
+ class _session_context_manager(object):
+ def __init__(self, server, sid):
+ self.server = server
+ self.sid = sid
+ self.session = None
+
+ def __enter__(self):
+ self.session = self.server.get_session(sid)
+ return self.session
+
+ def __exit__(self, *args):
+ self.server.save_session(sid, self.session)
+
+ return _session_context_manager(self, sid)
+
+ def disconnect(self, sid=None):
+ """Disconnect a client.
+
+ :param sid: The session id of the client to close. If this parameter
+ is not given, then all clients are closed.
+ """
+ if sid is not None:
+ try:
+ socket = self._get_socket(sid)
+ except KeyError: # pragma: no cover
+ # the socket was already closed or gone
+ pass
+ else:
+ socket.close()
+ if sid in self.sockets: # pragma: no cover
+ del self.sockets[sid]
+ else:
+ for client in self.sockets.values():
+ client.close()
+ self.sockets = {}
+
+ def handle_request(self, environ, start_response):
+ """Handle an HTTP request from the client.
+
+ This is the entry point of the Engine.IO application, using the same
+ interface as a WSGI application. For the typical usage, this function
+ is invoked by the :class:`Middleware` instance, but it can be invoked
+ directly when the middleware is not used.
+
+ :param environ: The WSGI environment.
+ :param start_response: The WSGI ``start_response`` function.
+
+ This function returns the HTTP response body to deliver to the client
+ as a byte sequence.
+ """
+ if self.cors_allowed_origins != []:
+ # Validate the origin header if present
+ # This is important for WebSocket more than for HTTP, since
+ # browsers only apply CORS controls to HTTP.
+ origin = environ.get('HTTP_ORIGIN')
+ if origin:
+ allowed_origins = self._cors_allowed_origins(environ)
+ if allowed_origins is not None and origin not in \
+ allowed_origins:
+ self._log_error_once(
+ origin + ' is not an accepted origin.', 'bad-origin')
+ r = self._bad_request('Not an accepted origin.')
+ start_response(r['status'], r['headers'])
+ return [r['response']]
+
+ method = environ['REQUEST_METHOD']
+ query = urllib.parse.parse_qs(environ.get('QUERY_STRING', ''))
+ jsonp = False
+ jsonp_index = None
+
+ # make sure the client uses an allowed transport
+ transport = query.get('transport', ['polling'])[0]
+ if transport not in self.transports:
+ self._log_error_once('Invalid transport', 'bad-transport')
+ r = self._bad_request('Invalid transport')
+ start_response(r['status'], r['headers'])
+ return [r['response']]
+
+ # make sure the client speaks a compatible Engine.IO version
+ sid = query['sid'][0] if 'sid' in query else None
+ if sid is None and query.get('EIO') != ['4']:
+ self._log_error_once(
+ 'The client is using an unsupported version of the Socket.IO '
+ 'or Engine.IO protocols', 'bad-version')
+ r = self._bad_request(
+ 'The client is using an unsupported version of the Socket.IO '
+ 'or Engine.IO protocols')
+ start_response(r['status'], r['headers'])
+ return [r['response']]
+
+ if 'j' in query:
+ jsonp = True
+ try:
+ jsonp_index = int(query['j'][0])
+ except (ValueError, KeyError, IndexError):
+ # Invalid JSONP index number
+ pass
+
+ if jsonp and jsonp_index is None:
+ self._log_error_once('Invalid JSONP index number',
+ 'bad-jsonp-index')
+ r = self._bad_request('Invalid JSONP index number')
+ elif method == 'GET':
+ if sid is None:
+ # transport must be one of 'polling' or 'websocket'.
+ # if 'websocket', the HTTP_UPGRADE header must match.
+ upgrade_header = environ.get('HTTP_UPGRADE').lower() \
+ if 'HTTP_UPGRADE' in environ else None
+ if transport == 'polling' \
+ or transport == upgrade_header == 'websocket':
+ r = self._handle_connect(environ, start_response,
+ transport, jsonp_index)
+ else:
+ self._log_error_once('Invalid websocket upgrade',
+ 'bad-upgrade')
+ r = self._bad_request('Invalid websocket upgrade')
+ else:
+ if sid not in self.sockets:
+ self._log_error_once('Invalid session ' + sid, 'bad-sid')
+ r = self._bad_request('Invalid session')
+ else:
+ socket = self._get_socket(sid)
+ try:
+ packets = socket.handle_get_request(
+ environ, start_response)
+ if isinstance(packets, list):
+ r = self._ok(packets, jsonp_index=jsonp_index)
+ else:
+ r = packets
+ except exceptions.EngineIOError:
+ if sid in self.sockets: # pragma: no cover
+ self.disconnect(sid)
+ r = self._bad_request()
+ if sid in self.sockets and self.sockets[sid].closed:
+ del self.sockets[sid]
+ elif method == 'POST':
+ if sid is None or sid not in self.sockets:
+ self._log_error_once(
+ 'Invalid session ' + (sid or 'None'), 'bad-sid')
+ r = self._bad_request('Invalid session')
+ else:
+ socket = self._get_socket(sid)
+ try:
+ socket.handle_post_request(environ)
+ r = self._ok(jsonp_index=jsonp_index)
+ except exceptions.EngineIOError:
+ if sid in self.sockets: # pragma: no cover
+ self.disconnect(sid)
+ r = self._bad_request()
+ except: # pragma: no cover
+ # for any other unexpected errors, we log the error
+ # and keep going
+ self.logger.exception('post request handler error')
+ r = self._ok(jsonp_index=jsonp_index)
+ elif method == 'OPTIONS':
+ r = self._ok()
+ else:
+ self.logger.warning('Method %s not supported', method)
+ r = self._method_not_found()
+
+ if not isinstance(r, dict):
+ return r
+ if self.http_compression and \
+ len(r['response']) >= self.compression_threshold:
+ encodings = [e.split(';')[0].strip() for e in
+ environ.get('HTTP_ACCEPT_ENCODING', '').split(',')]
+ for encoding in encodings:
+ if encoding in self.compression_methods:
+ r['response'] = \
+ getattr(self, '_' + encoding)(r['response'])
+ r['headers'] += [('Content-Encoding', encoding)]
+ break
+ cors_headers = self._cors_headers(environ)
+ start_response(r['status'], r['headers'] + cors_headers)
+ return [r['response']]
+
+ def shutdown(self):
+ """Stop Socket.IO background tasks.
+
+ This method stops background activity initiated by the Socket.IO
+ server. It must be called before shutting down the web server.
+ """
+ self.logger.info('Socket.IO is shutting down')
+ if self.service_task_event: # pragma: no cover
+ self.service_task_event.set()
+ self.service_task_handle.join()
+ self.service_task_handle = None
+
+ def start_background_task(self, target, *args, **kwargs):
+ """Start a background task using the appropriate async model.
+
+ This is a utility function that applications can use to start a
+ background task using the method that is compatible with the
+ selected async mode.
+
+ :param target: the target function to execute.
+ :param args: arguments to pass to the function.
+ :param kwargs: keyword arguments to pass to the function.
+
+ This function returns an object that represents the background task,
+ on which the ``join()`` methond can be invoked to wait for the task to
+ complete.
+ """
+ th = self._async['thread'](target=target, args=args, kwargs=kwargs)
+ th.start()
+ return th # pragma: no cover
+
+ def sleep(self, seconds=0):
+ """Sleep for the requested amount of time using the appropriate async
+ model.
+
+ This is a utility function that applications can use to put a task to
+ sleep without having to worry about using the correct call for the
+ selected async mode.
+ """
+ return self._async['sleep'](seconds)
+
+ def _handle_connect(self, environ, start_response, transport,
+ jsonp_index=None):
+ """Handle a client connection request."""
+ if self.start_service_task:
+ # start the service task to monitor connected clients
+ self.start_service_task = False
+ self.service_task_handle = self.start_background_task(
+ self._service_task)
+
+ sid = self.generate_id()
+ s = socket.Socket(self, sid)
+ self.sockets[sid] = s
+
+ pkt = packet.Packet(packet.OPEN, {
+ 'sid': sid,
+ 'upgrades': self._upgrades(sid, transport),
+ 'pingTimeout': int(self.ping_timeout * 1000),
+ 'pingInterval': int(
+ self.ping_interval + self.ping_interval_grace_period) * 1000})
+ s.send(pkt)
+ s.schedule_ping()
+
+ # NOTE: some sections below are marked as "no cover" to workaround
+ # what seems to be a bug in the coverage package. All the lines below
+ # are covered by tests, but some are not reported as such for some
+ # reason
+ ret = self._trigger_event('connect', sid, environ, run_async=False)
+ if ret is not None and ret is not True: # pragma: no cover
+ del self.sockets[sid]
+ self.logger.warning('Application rejected connection')
+ return self._unauthorized(ret or None)
+
+ if transport == 'websocket': # pragma: no cover
+ ret = s.handle_get_request(environ, start_response)
+ if s.closed and sid in self.sockets:
+ # websocket connection ended, so we are done
+ del self.sockets[sid]
+ return ret
+ else: # pragma: no cover
+ s.connected = True
+ headers = None
+ if self.cookie:
+ if isinstance(self.cookie, dict):
+ headers = [(
+ 'Set-Cookie',
+ self._generate_sid_cookie(sid, self.cookie)
+ )]
+ else:
+ headers = [(
+ 'Set-Cookie',
+ self._generate_sid_cookie(sid, {
+ 'name': self.cookie, 'path': '/', 'SameSite': 'Lax'
+ })
+ )]
+ try:
+ return self._ok(s.poll(), headers=headers,
+ jsonp_index=jsonp_index)
+ except exceptions.QueueEmpty:
+ return self._bad_request()
+
+ def _trigger_event(self, event, *args, **kwargs):
+ """Invoke an event handler."""
+ run_async = kwargs.pop('run_async', False)
+ if event in self.handlers:
+ def run_handler():
+ try:
+ return self.handlers[event](*args)
+ except:
+ self.logger.exception(event + ' handler error')
+ if event == 'connect':
+ # if connect handler raised error we reject the
+ # connection
+ return False
+
+ if run_async:
+ return self.start_background_task(run_handler)
+ else:
+ return run_handler()
+
+ def _service_task(self): # pragma: no cover
+ """Monitor connected clients and clean up those that time out."""
+ self.service_task_event = self.create_event()
+ while not self.service_task_event.is_set():
+ if len(self.sockets) == 0:
+ # nothing to do
+ if self.service_task_event.wait(timeout=self.ping_timeout):
+ break
+ continue
+
+ # go through the entire client list in a ping interval cycle
+ sleep_interval = float(self.ping_timeout) / len(self.sockets)
+
+ try:
+ # iterate over the current clients
+ for s in self.sockets.copy().values():
+ if s.closed:
+ try:
+ del self.sockets[s.sid]
+ except KeyError:
+ # the socket could have also been removed by
+ # the _get_socket() method from another thread
+ pass
+ elif not s.closing:
+ s.check_ping_timeout()
+ if self.service_task_event.wait(timeout=sleep_interval):
+ raise KeyboardInterrupt()
+ except (SystemExit, KeyboardInterrupt):
+ self.logger.info('service task canceled')
+ break
+ except:
+ # an unexpected exception has occurred, log it and continue
+ self.logger.exception('service task exception')
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/socket.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/socket.py
new file mode 100644
index 0000000000000000000000000000000000000000..de8fd354d04bd85f52cb301686a3cdfca9b4544a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/socket.py
@@ -0,0 +1,250 @@
+import sys
+import time
+
+from . import base_socket
+from . import exceptions
+from . import packet
+from . import payload
+
+
+class Socket(base_socket.BaseSocket):
+ """An Engine.IO socket."""
+ def poll(self):
+ """Wait for packets to send to the client."""
+ queue_empty = self.server.get_queue_empty_exception()
+ try:
+ packets = [self.queue.get(
+ timeout=self.server.ping_interval + self.server.ping_timeout)]
+ self.queue.task_done()
+ except queue_empty:
+ raise exceptions.QueueEmpty()
+ if packets == [None]:
+ return []
+ while True:
+ try:
+ pkt = self.queue.get(block=False)
+ self.queue.task_done()
+ if pkt is None:
+ self.queue.put(None)
+ break
+ packets.append(pkt)
+ except queue_empty:
+ break
+ return packets
+
+ def receive(self, pkt):
+ """Receive packet from the client."""
+ packet_name = packet.packet_names[pkt.packet_type] \
+ if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN'
+ self.server.logger.info('%s: Received packet %s data %s',
+ self.sid, packet_name,
+ pkt.data if not isinstance(pkt.data, bytes)
+ else '')
+ if pkt.packet_type == packet.PONG:
+ self.schedule_ping()
+ elif pkt.packet_type == packet.MESSAGE:
+ self.server._trigger_event('message', self.sid, pkt.data,
+ run_async=self.server.async_handlers)
+ elif pkt.packet_type == packet.UPGRADE:
+ self.send(packet.Packet(packet.NOOP))
+ elif pkt.packet_type == packet.CLOSE:
+ self.close(wait=False, abort=True)
+ else:
+ raise exceptions.UnknownPacketError()
+
+ def check_ping_timeout(self):
+ """Make sure the client is still responding to pings."""
+ if self.closed:
+ raise exceptions.SocketIsClosedError()
+ if self.last_ping and \
+ time.time() - self.last_ping > self.server.ping_timeout:
+ self.server.logger.info('%s: Client is gone, closing socket',
+ self.sid)
+ # Passing abort=False here will cause close() to write a
+ # CLOSE packet. This has the effect of updating half-open sockets
+ # to their correct state of disconnected
+ self.close(wait=False, abort=False)
+ return False
+ return True
+
+ def send(self, pkt):
+ """Send a packet to the client."""
+ if not self.check_ping_timeout():
+ return
+ else:
+ self.queue.put(pkt)
+ self.server.logger.info('%s: Sending packet %s data %s',
+ self.sid, packet.packet_names[pkt.packet_type],
+ pkt.data if not isinstance(pkt.data, bytes)
+ else '')
+
+ def handle_get_request(self, environ, start_response):
+ """Handle a long-polling GET request from the client."""
+ connections = [
+ s.strip()
+ for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
+ transport = environ.get('HTTP_UPGRADE', '').lower()
+ if 'upgrade' in connections and transport in self.upgrade_protocols:
+ self.server.logger.info('%s: Received request to upgrade to %s',
+ self.sid, transport)
+ return getattr(self, '_upgrade_' + transport)(environ,
+ start_response)
+ if self.upgrading or self.upgraded:
+ # we are upgrading to WebSocket, do not return any more packets
+ # through the polling endpoint
+ return [packet.Packet(packet.NOOP)]
+ try:
+ packets = self.poll()
+ except exceptions.QueueEmpty:
+ exc = sys.exc_info()
+ self.close(wait=False)
+ raise exc[1].with_traceback(exc[2])
+ return packets
+
+ def handle_post_request(self, environ):
+ """Handle a long-polling POST request from the client."""
+ length = int(environ.get('CONTENT_LENGTH', '0'))
+ if length > self.server.max_http_buffer_size:
+ raise exceptions.ContentTooLongError()
+ else:
+ body = environ['wsgi.input'].read(length).decode('utf-8')
+ p = payload.Payload(encoded_payload=body)
+ for pkt in p.packets:
+ self.receive(pkt)
+
+ def close(self, wait=True, abort=False):
+ """Close the socket connection."""
+ if not self.closed and not self.closing:
+ self.closing = True
+ self.server._trigger_event('disconnect', self.sid, run_async=False)
+ if not abort:
+ self.send(packet.Packet(packet.CLOSE))
+ self.closed = True
+ self.queue.put(None)
+ if wait:
+ self.queue.join()
+
+ def schedule_ping(self):
+ self.server.start_background_task(self._send_ping)
+
+ def _send_ping(self):
+ self.last_ping = None
+ self.server.sleep(self.server.ping_interval)
+ if not self.closing and not self.closed:
+ self.last_ping = time.time()
+ self.send(packet.Packet(packet.PING))
+
+ def _upgrade_websocket(self, environ, start_response):
+ """Upgrade the connection from polling to websocket."""
+ if self.upgraded:
+ raise IOError('Socket has been upgraded already')
+ if self.server._async['websocket'] is None:
+ # the selected async mode does not support websocket
+ return self.server._bad_request()
+ ws = self.server._async['websocket'](
+ self._websocket_handler, self.server)
+ return ws(environ, start_response)
+
+ def _websocket_handler(self, ws):
+ """Engine.IO handler for websocket transport."""
+ def websocket_wait():
+ data = ws.wait()
+ if data and len(data) > self.server.max_http_buffer_size:
+ raise ValueError('packet is too large')
+ return data
+
+ # try to set a socket timeout matching the configured ping interval
+ # and timeout
+ for attr in ['_sock', 'socket']: # pragma: no cover
+ if hasattr(ws, attr) and hasattr(getattr(ws, attr), 'settimeout'):
+ getattr(ws, attr).settimeout(
+ self.server.ping_interval + self.server.ping_timeout)
+
+ if self.connected:
+ # the socket was already connected, so this is an upgrade
+ self.upgrading = True # hold packet sends during the upgrade
+
+ pkt = websocket_wait()
+ decoded_pkt = packet.Packet(encoded_packet=pkt)
+ if decoded_pkt.packet_type != packet.PING or \
+ decoded_pkt.data != 'probe':
+ self.server.logger.info(
+ '%s: Failed websocket upgrade, no PING packet', self.sid)
+ self.upgrading = False
+ return []
+ ws.send(packet.Packet(packet.PONG, data='probe').encode())
+ self.queue.put(packet.Packet(packet.NOOP)) # end poll
+
+ pkt = websocket_wait()
+ decoded_pkt = packet.Packet(encoded_packet=pkt)
+ if decoded_pkt.packet_type != packet.UPGRADE:
+ self.upgraded = False
+ self.server.logger.info(
+ ('%s: Failed websocket upgrade, expected UPGRADE packet, '
+ 'received %s instead.'),
+ self.sid, pkt)
+ self.upgrading = False
+ return []
+ self.upgraded = True
+ self.upgrading = False
+ else:
+ self.connected = True
+ self.upgraded = True
+
+ # start separate writer thread
+ def writer():
+ while True:
+ packets = None
+ try:
+ packets = self.poll()
+ except exceptions.QueueEmpty:
+ break
+ if not packets:
+ # empty packet list returned -> connection closed
+ break
+ try:
+ for pkt in packets:
+ ws.send(pkt.encode())
+ except:
+ break
+ ws.close()
+
+ writer_task = self.server.start_background_task(writer)
+
+ self.server.logger.info(
+ '%s: Upgrade to websocket successful', self.sid)
+
+ while True:
+ p = None
+ try:
+ p = websocket_wait()
+ except Exception as e:
+ # if the socket is already closed, we can assume this is a
+ # downstream error of that
+ if not self.closed: # pragma: no cover
+ self.server.logger.info(
+ '%s: Unexpected error "%s", closing connection',
+ self.sid, str(e))
+ break
+ if p is None:
+ # connection closed by client
+ break
+ pkt = packet.Packet(encoded_packet=p)
+ try:
+ self.receive(pkt)
+ except exceptions.UnknownPacketError: # pragma: no cover
+ pass
+ except exceptions.SocketIsClosedError: # pragma: no cover
+ self.server.logger.info('Receive error -- socket is closed')
+ break
+ except: # pragma: no cover
+ # if we get an unexpected exception we log the error and exit
+ # the connection properly
+ self.server.logger.exception('Unknown receive error')
+ break
+
+ self.queue.put(None) # unlock the writer task so that it can exit
+ writer_task.join()
+ self.close(wait=False, abort=True)
+
+ return []
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/static_files.py b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/static_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..77c891571971cec0cace3a03ff2dabfbbcf1e8a1
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/engineio/static_files.py
@@ -0,0 +1,60 @@
+content_types = {
+ 'css': 'text/css',
+ 'gif': 'image/gif',
+ 'html': 'text/html',
+ 'jpg': 'image/jpeg',
+ 'js': 'application/javascript',
+ 'json': 'application/json',
+ 'png': 'image/png',
+ 'txt': 'text/plain',
+}
+
+
+def get_static_file(path, static_files):
+ """Return the local filename and content type for the requested static
+ file URL.
+
+ :param path: the path portion of the requested URL.
+ :param static_files: a static file configuration dictionary.
+
+ This function returns a dictionary with two keys, "filename" and
+ "content_type". If the requested URL does not match any static file, the
+ return value is None.
+ """
+ extra_path = ''
+ if path in static_files:
+ f = static_files[path]
+ else:
+ f = None
+ while path != '':
+ path, last = path.rsplit('/', 1)
+ extra_path = '/' + last + extra_path
+ if path in static_files:
+ f = static_files[path]
+ break
+ elif path + '/' in static_files:
+ f = static_files[path + '/']
+ break
+ if f:
+ if isinstance(f, str):
+ f = {'filename': f}
+ else:
+ f = f.copy() # in case it is mutated below
+ if f['filename'].endswith('/') and extra_path.startswith('/'):
+ extra_path = extra_path[1:]
+ f['filename'] += extra_path
+ if f['filename'].endswith('/'):
+ if '' in static_files:
+ if isinstance(static_files[''], str):
+ f['filename'] += static_files['']
+ else:
+ f['filename'] += static_files['']['filename']
+ if 'content_type' in static_files['']:
+ f['content_type'] = static_files['']['content_type']
+ else:
+ f['filename'] += 'index.html'
+ if 'content_type' not in f:
+ ext = f['filename'].rsplit('.')[-1]
+ f['content_type'] = content_types.get(
+ ext, 'application/octet-stream')
+ return f
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..a2576b7b6b3f7e7c02decf6494ad8c80c4202934
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/METADATA
@@ -0,0 +1,122 @@
+Metadata-Version: 2.1
+Name: eventlet
+Version: 0.34.2
+Summary: Highly concurrent networking library
+Project-URL: Homepage, https://github.com/eventlet/eventlet
+Project-URL: History, https://github.com/eventlet/eventlet/blob/master/NEWS
+Project-URL: Tracker, https://github.com/eventlet/eventlet/issues
+Project-URL: Source, https://github.com/eventlet/eventlet
+Author-email: Sergey Shepelev , Jakub Stasiak , Tim Burke , Nat Goodspeed , Itamar Turner-Trauring , Hervé Beraud
+License: MIT
+License-File: AUTHORS
+License-File: LICENSE
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Topic :: Internet
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.7
+Requires-Dist: dnspython>=1.15.0
+Requires-Dist: greenlet>=1.0
+Requires-Dist: monotonic>=1.4; python_version < '3.5'
+Requires-Dist: six>=1.10.0
+Provides-Extra: dev
+Requires-Dist: black; extra == 'dev'
+Requires-Dist: build; extra == 'dev'
+Requires-Dist: commitizen; extra == 'dev'
+Requires-Dist: isort; extra == 'dev'
+Requires-Dist: pip-tools; extra == 'dev'
+Requires-Dist: pre-commit; extra == 'dev'
+Requires-Dist: twine; extra == 'dev'
+Description-Content-Type: text/x-rst
+
+Eventlet is a concurrent networking library for Python that allows you to change how you run your code, not how you write it.
+
+It uses epoll or libevent for highly scalable non-blocking I/O. Coroutines ensure that the developer uses a blocking style of programming that is similar to threading, but provide the benefits of non-blocking I/O. The event dispatch is implicit, which means you can easily use Eventlet from the Python interpreter, or as a small part of a larger application.
+
+It's easy to get started using Eventlet, and easy to convert existing
+applications to use it. Start off by looking at the `examples`_,
+`common design patterns`_, and the list of `basic API primitives`_.
+
+.. _examples: http://eventlet.net/doc/examples.html
+.. _common design patterns: http://eventlet.net/doc/design_patterns.html
+.. _basic API primitives: http://eventlet.net/doc/basic_usage.html
+
+
+Quick Example
+===============
+
+Here's something you can try right on the command line::
+
+ % python3
+ >>> import eventlet
+ >>> from eventlet.green.urllib.request import urlopen
+ >>> gt = eventlet.spawn(urlopen, 'http://eventlet.net')
+ >>> gt2 = eventlet.spawn(urlopen, 'http://secondlife.com')
+ >>> gt2.wait()
+ >>> gt.wait()
+
+
+Getting Eventlet
+==================
+
+The easiest way to get Eventlet is to use pip::
+
+ pip install -U eventlet
+
+To install latest development version once::
+
+ pip install -U https://github.com/eventlet/eventlet/archive/master.zip
+
+
+Building the Docs Locally
+=========================
+
+To build a complete set of HTML documentation, you must have Sphinx, which can be found at http://sphinx.pocoo.org/ (or installed with `pip install Sphinx`)::
+
+ cd doc
+ make html
+
+The built html files can be found in doc/_build/html afterward.
+
+
+Twisted
+=======
+
+Eventlet had Twisted hub in the past, but community interest to this integration has dropped over time,
+now it is not supported, so with apologies for any inconvenience we discontinue Twisted integration.
+
+If you have a project that uses Eventlet with Twisted, your options are:
+
+* use last working release eventlet==0.14
+* start a new project with only Twisted hub code, identify and fix problems. As of eventlet 0.13, `EVENTLET_HUB` environment variable can point to external modules.
+* fork Eventlet, revert Twisted removal, identify and fix problems. This work may be merged back into main project.
+
+Apologies for any inconvenience.
+
+Supported Python versions
+=========================
+
+Python 3.7-3.12 are currently supported.
+
+Flair
+=====
+
+.. image:: https://img.shields.io/pypi/v/eventlet
+ :target: https://pypi.org/project/eventlet/
+
+.. image:: https://img.shields.io/github/actions/workflow/status/eventlet/eventlet/test.yaml?branch=master
+ :target: https://github.com/eventlet/eventlet/actions?query=workflow%3Atest+branch%3Amaster
+
+.. image:: https://codecov.io/gh/eventlet/eventlet/branch/master/graph/badge.svg
+ :target: https://codecov.io/gh/eventlet/eventlet
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..ebdaf92dd286f26c52a827c16e54a1a0c28cf8ae
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/RECORD
@@ -0,0 +1,197 @@
+eventlet-0.34.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+eventlet-0.34.2.dist-info/METADATA,sha256=kpAoeuhvqEuCe_K6zhR1kZVM-dEMqgNioTpoP02jlk4,4842
+eventlet-0.34.2.dist-info/RECORD,,
+eventlet-0.34.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+eventlet-0.34.2.dist-info/WHEEL,sha256=mRYSEL3Ih6g5a_CVMIcwiF__0Ae4_gLYh01YFNwiq1k,87
+eventlet-0.34.2.dist-info/licenses/AUTHORS,sha256=qyCotEDXx0wuNTpDiFDomaSiPUSTrZm49r3m8LsMmY0,5837
+eventlet-0.34.2.dist-info/licenses/LICENSE,sha256=vOygSX96gUdRFr_0E4cz-yAGC2sitnHmV7YVioYGVuI,1254
+eventlet/__init__.py,sha256=txpANlWkGgYBAuIRk0QJElXPM4Oz2l2-5_lPvHjZmCw,2469
+eventlet/__pycache__/__init__.cpython-311.pyc,,
+eventlet/__pycache__/_version.cpython-311.pyc,,
+eventlet/__pycache__/backdoor.cpython-311.pyc,,
+eventlet/__pycache__/convenience.cpython-311.pyc,,
+eventlet/__pycache__/corolocal.cpython-311.pyc,,
+eventlet/__pycache__/coros.cpython-311.pyc,,
+eventlet/__pycache__/dagpool.cpython-311.pyc,,
+eventlet/__pycache__/db_pool.cpython-311.pyc,,
+eventlet/__pycache__/debug.cpython-311.pyc,,
+eventlet/__pycache__/event.cpython-311.pyc,,
+eventlet/__pycache__/greenpool.cpython-311.pyc,,
+eventlet/__pycache__/greenthread.cpython-311.pyc,,
+eventlet/__pycache__/lock.cpython-311.pyc,,
+eventlet/__pycache__/patcher.cpython-311.pyc,,
+eventlet/__pycache__/pools.cpython-311.pyc,,
+eventlet/__pycache__/queue.cpython-311.pyc,,
+eventlet/__pycache__/semaphore.cpython-311.pyc,,
+eventlet/__pycache__/timeout.cpython-311.pyc,,
+eventlet/__pycache__/tpool.cpython-311.pyc,,
+eventlet/__pycache__/websocket.cpython-311.pyc,,
+eventlet/__pycache__/wsgi.cpython-311.pyc,,
+eventlet/_version.py,sha256=c_vxGYmDK2jtU8bUhurHm8rAvLUikWt_OATipkAEPlo,413
+eventlet/backdoor.py,sha256=-Uv0ckydgiCtGMIZ8ki_SGIaJPEvJKKKz0fu-RrBCl4,4130
+eventlet/convenience.py,sha256=9tRR0CopB3PbTKBbtSmW85gPTgNEEle6HMLsG77B7Z8,7174
+eventlet/corolocal.py,sha256=XLpOq3jdWyRxwvD9esg3edoGBIDSZ2NSZqX1WXeosAU,1741
+eventlet/coros.py,sha256=horXHsHTANuqNzWRY4wC-54OUVSy8ERC8U2jQKE-kUU,2077
+eventlet/dagpool.py,sha256=EvLUDyvKE_jWlkiwiA97E_-OR2zvjRWxekMVwGuIM34,26303
+eventlet/db_pool.py,sha256=97j1JikXk8S-e9nhdBY2SlalLR_NRX24qLOCJG9m_hg,15765
+eventlet/debug.py,sha256=B6as5ianRkkwKGzE3o4iWEMh93gTnhB9316w0En3cmk,6326
+eventlet/event.py,sha256=f1jNUThzwQmD87NQymXv-8FP32WErVKt11Rp6NWIDc4,7519
+eventlet/green/BaseHTTPServer.py,sha256=2Ft0aojrxibdqpoeMlv7kcJi_QzFWbsbVbQ798wQOQg,346
+eventlet/green/CGIHTTPServer.py,sha256=BKc7T1hs9ZG9BWIAYih9D5Dq6OYqv_ntEo4LcDIC2mA,552
+eventlet/green/MySQLdb.py,sha256=F15muNnciOG1WcrZndC3j87X0Ksgb6Bc3kPG7waxExs,1204
+eventlet/green/OpenSSL/SSL.py,sha256=1hFS2eB30LGZDgbLTrCMH7htDbRreBVLtXgNmiJ50tk,4534
+eventlet/green/OpenSSL/__init__.py,sha256=h3kX23byJXMSl1rEhBf1oPo5D9LLqmXjWngXmaHpON0,246
+eventlet/green/OpenSSL/__pycache__/SSL.cpython-311.pyc,,
+eventlet/green/OpenSSL/__pycache__/__init__.cpython-311.pyc,,
+eventlet/green/OpenSSL/__pycache__/crypto.cpython-311.pyc,,
+eventlet/green/OpenSSL/__pycache__/tsafe.cpython-311.pyc,,
+eventlet/green/OpenSSL/__pycache__/version.cpython-311.pyc,,
+eventlet/green/OpenSSL/crypto.py,sha256=dcnjSGP6K274eAxalZEOttUZ1djAStBnbRH-wGBSJu4,29
+eventlet/green/OpenSSL/tsafe.py,sha256=DuY1rHdT2R0tiJkD13ECj-IU7_v-zQKjhTsK6CG8UEM,28
+eventlet/green/OpenSSL/version.py,sha256=3Ti2k01zP3lM6r0YuLbLS_QReJBEHaTJt5k0dNdXtI4,49
+eventlet/green/Queue.py,sha256=X0GjCILYok8CdHDWKCV9KjNJQgoogjL3M8sABT7SsNc,834
+eventlet/green/SimpleHTTPServer.py,sha256=WkrEBwvEdUNuKCJp1n4NY_4x_xhJR-lfws-BWbfclOA,277
+eventlet/green/SocketServer.py,sha256=wkmsIglVoBXR-XuRevVmEopJ4ylQtCXCXp1f-pVooiw,365
+eventlet/green/__init__.py,sha256=upnrKC57DQQBDNvpxXf_IhDapQ6NtEt2hgxIs1pZDao,84
+eventlet/green/__pycache__/BaseHTTPServer.cpython-311.pyc,,
+eventlet/green/__pycache__/CGIHTTPServer.cpython-311.pyc,,
+eventlet/green/__pycache__/MySQLdb.cpython-311.pyc,,
+eventlet/green/__pycache__/Queue.cpython-311.pyc,,
+eventlet/green/__pycache__/SimpleHTTPServer.cpython-311.pyc,,
+eventlet/green/__pycache__/SocketServer.cpython-311.pyc,,
+eventlet/green/__pycache__/__init__.cpython-311.pyc,,
+eventlet/green/__pycache__/_socket_nodns.cpython-311.pyc,,
+eventlet/green/__pycache__/asynchat.cpython-311.pyc,,
+eventlet/green/__pycache__/asyncore.cpython-311.pyc,,
+eventlet/green/__pycache__/builtin.cpython-311.pyc,,
+eventlet/green/__pycache__/ftplib.cpython-311.pyc,,
+eventlet/green/__pycache__/httplib.cpython-311.pyc,,
+eventlet/green/__pycache__/os.cpython-311.pyc,,
+eventlet/green/__pycache__/profile.cpython-311.pyc,,
+eventlet/green/__pycache__/select.cpython-311.pyc,,
+eventlet/green/__pycache__/selectors.cpython-311.pyc,,
+eventlet/green/__pycache__/socket.cpython-311.pyc,,
+eventlet/green/__pycache__/ssl.cpython-311.pyc,,
+eventlet/green/__pycache__/subprocess.cpython-311.pyc,,
+eventlet/green/__pycache__/thread.cpython-311.pyc,,
+eventlet/green/__pycache__/threading.cpython-311.pyc,,
+eventlet/green/__pycache__/time.cpython-311.pyc,,
+eventlet/green/__pycache__/urllib2.cpython-311.pyc,,
+eventlet/green/__pycache__/zmq.cpython-311.pyc,,
+eventlet/green/_socket_nodns.py,sha256=Oc-5EYs3AST-0HH4Hpi24t2tLp_CrzRX3jDFHN_rPH4,795
+eventlet/green/asynchat.py,sha256=IxG7yS4UNv2z8xkbtlnyGrAGpaXIjYGpyxtXjmcgWrI,291
+eventlet/green/asyncore.py,sha256=aKGWNcWSKUJhWS5fC5i9SrcIWyPuHQxaQKks8yw_m50,345
+eventlet/green/builtin.py,sha256=zg5ipE7NlFWs6UWGZQuKhQ6lZAmYdW7Y5iZlg5AZtK0,1287
+eventlet/green/ftplib.py,sha256=d23VMcAPqw7ZILheDJmueM8qOlWHnq0WFjjSgWouRdA,307
+eventlet/green/http/__init__.py,sha256=ve29vEVORq8ZV-_mp6ULOhZUGjdKkSnAISiFDwLhZd4,8793
+eventlet/green/http/__pycache__/__init__.cpython-311.pyc,,
+eventlet/green/http/__pycache__/client.cpython-311.pyc,,
+eventlet/green/http/__pycache__/cookiejar.cpython-311.pyc,,
+eventlet/green/http/__pycache__/cookies.cpython-311.pyc,,
+eventlet/green/http/__pycache__/server.cpython-311.pyc,,
+eventlet/green/http/client.py,sha256=R5nGXRw7tW0vGVeZeDcBpU5Ch8wzr8tK0Uy6yRpjr4A,59227
+eventlet/green/http/cookiejar.py,sha256=0HSmj_sac1TlnGDxJ27dSezwljwOvlAdUH_Bt3-Wy-w,79240
+eventlet/green/http/cookies.py,sha256=6ZJL0cirlTaG9Rmohy5M9NfwMkYRRbJxly8Nrd4446s,24188
+eventlet/green/http/server.py,sha256=jHfdMtiF8_WQHahLCEspBHpm2cCm7wmBKbBRByn7vQs,46596
+eventlet/green/httplib.py,sha256=a3RJ82XL7Z_2TbYBcvUeQ7S8d82jhmEITrUq6MNTMws,493
+eventlet/green/os.py,sha256=cx16KfYXv4NROjL-UnWF3KugGIKE_c2wyHYDOgPMo9o,3403
+eventlet/green/profile.py,sha256=ROmWKx2ZThDlYdchObK0sUB0lup7J-UgFx5CoqFWwdQ,9554
+eventlet/green/select.py,sha256=Yay3PQaRZRkfTZyylZi7utQXHsvtv8HB_QWNVfpvEUs,2769
+eventlet/green/selectors.py,sha256=C_aeln-t0FsMG2WosmkIBhGst0KfKglcaJG8U50pxQM,948
+eventlet/green/socket.py,sha256=np5_HqSjA4_y_kYKdSFyHQN0vjzLW_qi_oLFH8bB0T0,1918
+eventlet/green/ssl.py,sha256=nkfZ4uCb5yL6pVjoY0QZGr-OMV6ZftjKqAQE0I-xN5o,21292
+eventlet/green/subprocess.py,sha256=GRTiwbwzduBxOpEsvulVnu8sBkO_iCR66E1CK1GvqxE,5837
+eventlet/green/thread.py,sha256=mUoXjvVb2eSfYh8DF0rAjSOSKDEE6vA6PlUv56Sf380,3326
+eventlet/green/threading.py,sha256=TDVDXRUuLmidHDhHXGnCRM0Ih-XyqRFCEByDn0wbufI,3875
+eventlet/green/time.py,sha256=1W7BKbGrfTI1v2-pDnBvzBn01tbQ8zwyqz458BFrjt0,240
+eventlet/green/urllib/__init__.py,sha256=9tOImBCBOp1wPQ0C8UkfJ_9KJLwN0IDYZcLiSKd1N8E,1401
+eventlet/green/urllib/__pycache__/__init__.cpython-311.pyc,,
+eventlet/green/urllib/__pycache__/error.cpython-311.pyc,,
+eventlet/green/urllib/__pycache__/parse.cpython-311.pyc,,
+eventlet/green/urllib/__pycache__/request.cpython-311.pyc,,
+eventlet/green/urllib/__pycache__/response.cpython-311.pyc,,
+eventlet/green/urllib/error.py,sha256=xlpHJIa8U4QTFolAa3NEy5gEVj_nM3oF2bB-FvdhCQg,157
+eventlet/green/urllib/parse.py,sha256=uJ1R4rbgqlQgINjKm_-oTxveLvCR9anu7U0i7aRS87k,83
+eventlet/green/urllib/request.py,sha256=Upa4bT0-9pSxJOmPuIk3t1rNmGbLEkAOUlpD4aUfCGM,1504
+eventlet/green/urllib/response.py,sha256=ytsGn0pXE94tlZh75hl9X1cFGagjGNBWm6k_PRXOBmM,86
+eventlet/green/urllib2.py,sha256=Su3dEhDc8VsKK9PqhIXwgFVOOHVI37TTXU_beqzvg44,488
+eventlet/green/zmq.py,sha256=13lNAeopktRk3X273weSfTx4ZOjVXC0ZrUcOtQpoKYw,18067
+eventlet/greenio/__init__.py,sha256=U-_kIaeIjRmZOSfrzUOWjjhqJETuO4A79KWgua4foYc,169
+eventlet/greenio/__pycache__/__init__.cpython-311.pyc,,
+eventlet/greenio/__pycache__/base.cpython-311.pyc,,
+eventlet/greenio/__pycache__/py2.cpython-311.pyc,,
+eventlet/greenio/__pycache__/py3.cpython-311.pyc,,
+eventlet/greenio/base.py,sha256=hROynTdsfnuqwmtaja1uviLkTGDZGLBuqamP23OvqkE,18168
+eventlet/greenio/py2.py,sha256=cOQ1iL0-15YKvJ6jgQ7dIN6gJMhtcWUwOjGPYzZyj3U,6814
+eventlet/greenio/py3.py,sha256=F-kXv3AsFxt3q0qUjerJfmOzbB5g_hnUOINaPHmd680,6590
+eventlet/greenpool.py,sha256=01zT2bQGYY9njOt_mEsSO4-HxvYKq7dAl-yanJseQHg,9825
+eventlet/greenthread.py,sha256=HXFNahn2vabPXmM1OOeirj601001MFra5Js8EBOQYOc,11597
+eventlet/hubs/__init__.py,sha256=aySh7bqyelv8_fPyska6L5UZBIV-9W_4r4By5lhVL3w,5962
+eventlet/hubs/__pycache__/__init__.cpython-311.pyc,,
+eventlet/hubs/__pycache__/epolls.cpython-311.pyc,,
+eventlet/hubs/__pycache__/hub.cpython-311.pyc,,
+eventlet/hubs/__pycache__/kqueue.cpython-311.pyc,,
+eventlet/hubs/__pycache__/poll.cpython-311.pyc,,
+eventlet/hubs/__pycache__/pyevent.cpython-311.pyc,,
+eventlet/hubs/__pycache__/selects.cpython-311.pyc,,
+eventlet/hubs/__pycache__/timer.cpython-311.pyc,,
+eventlet/hubs/epolls.py,sha256=h55rCw84ZTCU4iHK0FKoIHSa-ZqhZNXK6KaTOKBkN9w,1027
+eventlet/hubs/hub.py,sha256=2qLdYK_Z7Rsup1CrvkcXf_hLZcEDem67Ajzm0pzhSyE,17665
+eventlet/hubs/kqueue.py,sha256=-KVuo8jDo4PJ07b3KRSbe1OAcPg_gGIEsy802_0L6M8,3501
+eventlet/hubs/poll.py,sha256=79IJPKxV-_lNsJv_X_1gxP3xtOZOmluj1XXqdHW6NLs,3976
+eventlet/hubs/pyevent.py,sha256=PtImWgRlaH9NmglMcAw5BnqYrTnVoy-4VjfRHUSdvyo,156
+eventlet/hubs/selects.py,sha256=7NfYI9jzkHhBbIKFLq68EevgO-XreX08qX0lNGl1fc0,2005
+eventlet/hubs/timer.py,sha256=y0TJFRGRgHZchJXZSodWhY4FpnrC9wuMfr7VMbJ42fc,3195
+eventlet/lock.py,sha256=GGrKyItc5a0ANCrB2eS7243g_BiHVAS_ufjy1eWE7Es,1229
+eventlet/patcher.py,sha256=eqH3lES03kVVRhKZpqZPfTXznvzWsbAfBHYhngK-mOg,20738
+eventlet/pools.py,sha256=LuqUR_95_fNuppZ6OK9CVIj2JxsUttc7HL-tqHnRsmo,6299
+eventlet/queue.py,sha256=hGMLS5ztBwHGepwW8hxAnwIkv2qbgVTTdt61eUPvlF8,18282
+eventlet/semaphore.py,sha256=0ZV1Uf9D1-0av2rTOqstiIjkHX6xz6F8-cowqtQUgXI,12226
+eventlet/support/__init__.py,sha256=Gkqs5h-VXQZc73NIkBXps45uuFdRLrXvme4DNwY3Y3k,1764
+eventlet/support/__pycache__/__init__.cpython-311.pyc,,
+eventlet/support/__pycache__/greendns.cpython-311.pyc,,
+eventlet/support/__pycache__/greenlets.cpython-311.pyc,,
+eventlet/support/__pycache__/psycopg2_patcher.cpython-311.pyc,,
+eventlet/support/__pycache__/pylib.cpython-311.pyc,,
+eventlet/support/__pycache__/stacklesspypys.cpython-311.pyc,,
+eventlet/support/__pycache__/stacklesss.cpython-311.pyc,,
+eventlet/support/greendns.py,sha256=Nuy2MH-m8p8xCkwL5WYb4V18XJ2smjqYRver9ZgxJ_I,34776
+eventlet/support/greenlets.py,sha256=1mxaAJJlZYSBgoWM1EL9IvbtMHTo61KokzScSby1Qy8,133
+eventlet/support/psycopg2_patcher.py,sha256=Rzm9GYS7PmrNpKAw04lqJV7KPcxLovnaCUI8CXE328A,2272
+eventlet/support/pylib.py,sha256=EvZ1JZEX3wqWtzfga5HeVL-sLLb805_f_ywX2k5BDHo,274
+eventlet/support/stacklesspypys.py,sha256=6BwZcnsCtb1m4wdK6GygoiPvYV03v7P7YlBxPIE6Zns,275
+eventlet/support/stacklesss.py,sha256=aZfBXegfo_-jGl3-lAaZGTeXs0ulA7CleF9qPRNHq8s,1867
+eventlet/timeout.py,sha256=mFW8oEj3wxSFQQhXOejdtOyWYaqFgRK82ccfz5fojQ4,6644
+eventlet/tpool.py,sha256=_Tjl8nyF9eAQGjK68YI1gfFVjCSAj90EeMicbelR5D0,10765
+eventlet/websocket.py,sha256=2kyV9pstgq29nwMBN1LmZSgzhIyZOlfHdeAXtusW_54,34443
+eventlet/wsgi.py,sha256=NZllatvSc5nYaR3UAr_HQF4ddfILiz1ovfgCqrFo2TE,39644
+eventlet/zipkin/README.rst,sha256=xmt_Mmbtl3apFwYzgrWOtaQdM46AdT1MV11N-dwrLsA,3866
+eventlet/zipkin/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+eventlet/zipkin/__pycache__/__init__.cpython-311.pyc,,
+eventlet/zipkin/__pycache__/api.cpython-311.pyc,,
+eventlet/zipkin/__pycache__/client.cpython-311.pyc,,
+eventlet/zipkin/__pycache__/greenthread.cpython-311.pyc,,
+eventlet/zipkin/__pycache__/http.cpython-311.pyc,,
+eventlet/zipkin/__pycache__/log.cpython-311.pyc,,
+eventlet/zipkin/__pycache__/patcher.cpython-311.pyc,,
+eventlet/zipkin/__pycache__/wsgi.cpython-311.pyc,,
+eventlet/zipkin/_thrift/README.rst,sha256=5bZ4doepGQlXdemHzPfvcobc5C0Mwa0lxzuAn_Dm3LY,233
+eventlet/zipkin/_thrift/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+eventlet/zipkin/_thrift/__pycache__/__init__.cpython-311.pyc,,
+eventlet/zipkin/_thrift/zipkinCore.thrift,sha256=zbV8L5vQUXNngVbI1eXR2gAgenmWRyPGzf7QEb2_wNU,2121
+eventlet/zipkin/_thrift/zipkinCore/__init__.py,sha256=YFcZTT8Cm-6Y4oTiCaqq0DT1lw2W09WqoEc5_pTAwW0,34
+eventlet/zipkin/_thrift/zipkinCore/__pycache__/__init__.cpython-311.pyc,,
+eventlet/zipkin/_thrift/zipkinCore/__pycache__/constants.cpython-311.pyc,,
+eventlet/zipkin/_thrift/zipkinCore/__pycache__/ttypes.cpython-311.pyc,,
+eventlet/zipkin/_thrift/zipkinCore/constants.py,sha256=cbgWT_mN04BRZbyzjr1LzT40xvotzFyz-vbYp8Q_klo,275
+eventlet/zipkin/_thrift/zipkinCore/ttypes.py,sha256=94RG3YtkmpeMmJ-EvKiwnYUtovYlfjrRVnh6sI27cJ0,13497
+eventlet/zipkin/api.py,sha256=8h3YuMLuKpwUuzRmGeCFRR_JC3QoduOKAFXnQFiyDa8,5444
+eventlet/zipkin/client.py,sha256=JXa6xSLgJ11xbNS0qPf9Hpo2MSdJMU8FPhZZ7bNIvNA,1699
+eventlet/zipkin/example/ex1.png,sha256=tMloQ9gWouUjGhHWTBzzuPQ308JdUtrVFd2ClXHRIBg,53179
+eventlet/zipkin/example/ex2.png,sha256=AAIYZig2qVz6RVTj8nlIKju0fYT3DfP-F28LLwYIxwI,40482
+eventlet/zipkin/example/ex3.png,sha256=xc4J1WOjKCeAYr4gRSFFggJbHMEk-_C9ukmAKXTEfuk,73175
+eventlet/zipkin/greenthread.py,sha256=ify1VnsJmrFneAwfPl6QE8kgHIPJE5fAE9Ks9wQzeVI,843
+eventlet/zipkin/http.py,sha256=qNd89Fq5iv4xXri_zTJyW9IKjjHa4dF8CWiX8R6KRxg,1767
+eventlet/zipkin/log.py,sha256=jElBHT8H3_vs9T3r8Q-JG30xyajQ7u6wNGWmmMPQ4AA,337
+eventlet/zipkin/patcher.py,sha256=t1g5tXcbuEvNix3ICtZyuIWaJKQtUHJ5ZUqsi14j9Dc,1388
+eventlet/zipkin/wsgi.py,sha256=732J1h_VKs3iAUynQ76joXYZDIA3utU0dF_-_H5qYBM,2276
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..2860816abecb3c5ad7da6d018a4334b87e6b6cfc
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet-0.34.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.21.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..959af3fd6456c100696b8322c17376fb4113dd7c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/__init__.py
@@ -0,0 +1,84 @@
+import os
+import sys
+import warnings
+
+if sys.version_info < (3, 5):
+ warnings.warn(
+ "Support for your Python version is deprecated and will be removed in the future",
+ DeprecationWarning,
+ )
+
+from eventlet import convenience
+from eventlet import event
+from eventlet import greenpool
+from eventlet import greenthread
+from eventlet import patcher
+from eventlet import queue
+from eventlet import semaphore
+from eventlet import support
+from eventlet import timeout
+# NOTE(hberaud): Versions are now managed by hatch and control version.
+# hatch has a build hook which generates the version file, however,
+# if the project is installed in editable mode then the _version.py file
+# will not be updated unless the package is reinstalled (or locally rebuilt).
+# For further details, please read:
+# https://github.com/ofek/hatch-vcs#build-hook
+# https://github.com/maresb/hatch-vcs-footgun-example
+try:
+ from eventlet._version import __version__
+except ImportError:
+ __version__ = "0.0.0"
+import greenlet
+
+# Force monotonic library search as early as possible.
+# Helpful when CPython < 3.5 on Linux blocked in `os.waitpid(-1)` before first use of hub.
+# Example: gunicorn
+# https://github.com/eventlet/eventlet/issues/401#issuecomment-327500352
+try:
+ import monotonic
+ del monotonic
+except ImportError:
+ pass
+
+connect = convenience.connect
+listen = convenience.listen
+serve = convenience.serve
+StopServe = convenience.StopServe
+wrap_ssl = convenience.wrap_ssl
+
+Event = event.Event
+
+GreenPool = greenpool.GreenPool
+GreenPile = greenpool.GreenPile
+
+sleep = greenthread.sleep
+spawn = greenthread.spawn
+spawn_n = greenthread.spawn_n
+spawn_after = greenthread.spawn_after
+kill = greenthread.kill
+
+import_patched = patcher.import_patched
+monkey_patch = patcher.monkey_patch
+
+Queue = queue.Queue
+
+Semaphore = semaphore.Semaphore
+CappedSemaphore = semaphore.CappedSemaphore
+BoundedSemaphore = semaphore.BoundedSemaphore
+
+Timeout = timeout.Timeout
+with_timeout = timeout.with_timeout
+wrap_is_timeout = timeout.wrap_is_timeout
+is_timeout = timeout.is_timeout
+
+getcurrent = greenlet.greenlet.getcurrent
+
+# deprecated
+TimeoutError, exc_after, call_after_global = (
+ support.wrap_deprecated(old, new)(fun) for old, new, fun in (
+ ('TimeoutError', 'Timeout', Timeout),
+ ('exc_after', 'greenthread.exc_after', greenthread.exc_after),
+ ('call_after_global', 'greenthread.call_after_global', greenthread.call_after_global),
+ ))
+
+os
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4a017540f344d75740147f342e0d0b31f122d66
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/_version.py
@@ -0,0 +1,16 @@
+# file generated by setuptools_scm
+# don't change, don't track in version control
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from typing import Tuple, Union
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
+else:
+ VERSION_TUPLE = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+
+__version__ = version = '0.34.2'
+__version_tuple__ = version_tuple = (0, 34, 2)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/backdoor.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/backdoor.py
new file mode 100644
index 0000000000000000000000000000000000000000..f49a969a6fc7ffe607f02c3822b339928912d508
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/backdoor.py
@@ -0,0 +1,144 @@
+from __future__ import print_function
+
+from code import InteractiveConsole
+import errno
+import socket
+import sys
+import errno
+import traceback
+
+import eventlet
+from eventlet import hubs
+from eventlet.support import greenlets, get_errno
+
+try:
+ sys.ps1
+except AttributeError:
+ sys.ps1 = '>>> '
+try:
+ sys.ps2
+except AttributeError:
+ sys.ps2 = '... '
+
+
+class FileProxy(object):
+ def __init__(self, f):
+ self.f = f
+
+ def isatty(self):
+ return True
+
+ def flush(self):
+ pass
+
+ def write(self, data, *a, **kw):
+ try:
+ self.f.write(data, *a, **kw)
+ self.f.flush()
+ except socket.error as e:
+ if get_errno(e) != errno.EPIPE:
+ raise
+
+ def readline(self, *a):
+ return self.f.readline(*a).replace('\r\n', '\n')
+
+ def __getattr__(self, attr):
+ return getattr(self.f, attr)
+
+
+# @@tavis: the `locals` args below mask the built-in function. Should
+# be renamed.
+class SocketConsole(greenlets.greenlet):
+ def __init__(self, desc, hostport, locals):
+ self.hostport = hostport
+ self.locals = locals
+ # mangle the socket
+ self.desc = FileProxy(desc)
+ greenlets.greenlet.__init__(self)
+
+ def run(self):
+ try:
+ console = InteractiveConsole(self.locals)
+ console.interact()
+ finally:
+ self.switch_out()
+ self.finalize()
+
+ def switch(self, *args, **kw):
+ self.saved = sys.stdin, sys.stderr, sys.stdout
+ sys.stdin = sys.stdout = sys.stderr = self.desc
+ greenlets.greenlet.switch(self, *args, **kw)
+
+ def switch_out(self):
+ sys.stdin, sys.stderr, sys.stdout = self.saved
+
+ def finalize(self):
+ # restore the state of the socket
+ self.desc = None
+ if len(self.hostport) >= 2:
+ host = self.hostport[0]
+ port = self.hostport[1]
+ print("backdoor closed to %s:%s" % (host, port,))
+ else:
+ print('backdoor closed')
+
+
+def backdoor_server(sock, locals=None):
+ """ Blocking function that runs a backdoor server on the socket *sock*,
+ accepting connections and running backdoor consoles for each client that
+ connects.
+
+ The *locals* argument is a dictionary that will be included in the locals()
+ of the interpreters. It can be convenient to stick important application
+ variables in here.
+ """
+ listening_on = sock.getsockname()
+ if sock.family == socket.AF_INET:
+ # Expand result to IP + port
+ listening_on = '%s:%s' % listening_on
+ elif sock.family == socket.AF_INET6:
+ ip, port, _, _ = listening_on
+ listening_on = '%s:%s' % (ip, port,)
+ # No action needed if sock.family == socket.AF_UNIX
+
+ print("backdoor server listening on %s" % (listening_on,))
+ try:
+ while True:
+ socketpair = None
+ try:
+ socketpair = sock.accept()
+ backdoor(socketpair, locals)
+ except socket.error as e:
+ # Broken pipe means it was shutdown
+ if get_errno(e) != errno.EPIPE:
+ raise
+ finally:
+ if socketpair:
+ socketpair[0].close()
+ finally:
+ sock.close()
+
+
+def backdoor(conn_info, locals=None):
+ """Sets up an interactive console on a socket with a single connected
+ client. This does not block the caller, as it spawns a new greenlet to
+ handle the console. This is meant to be called from within an accept loop
+ (such as backdoor_server).
+ """
+ conn, addr = conn_info
+ if conn.family == socket.AF_INET:
+ host, port = addr
+ print("backdoor to %s:%s" % (host, port))
+ elif conn.family == socket.AF_INET6:
+ host, port, _, _ = addr
+ print("backdoor to %s:%s" % (host, port))
+ else:
+ print('backdoor opened')
+ fl = conn.makefile("rw")
+ console = SocketConsole(fl, addr, locals)
+ hub = hubs.get_hub()
+ hub.schedule_call_global(0, console.switch)
+
+
+if __name__ == '__main__':
+ backdoor_server(eventlet.listen(('127.0.0.1', 9000)), {})
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/convenience.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/convenience.py
new file mode 100644
index 0000000000000000000000000000000000000000..a02284dee6ffb432d4b375dfb8c6f89a52474624
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/convenience.py
@@ -0,0 +1,190 @@
+import sys
+import warnings
+
+from eventlet import greenpool
+from eventlet import greenthread
+from eventlet import support
+from eventlet.green import socket
+from eventlet.support import greenlets as greenlet
+
+
+def connect(addr, family=socket.AF_INET, bind=None):
+ """Convenience function for opening client sockets.
+
+ :param addr: Address of the server to connect to. For TCP sockets, this is a (host, port) tuple.
+ :param family: Socket family, optional. See :mod:`socket` documentation for available families.
+ :param bind: Local address to bind to, optional.
+ :return: The connected green socket object.
+ """
+ sock = socket.socket(family, socket.SOCK_STREAM)
+ if bind is not None:
+ sock.bind(bind)
+ sock.connect(addr)
+ return sock
+
+
+class ReuseRandomPortWarning(Warning):
+ pass
+
+
+class ReusePortUnavailableWarning(Warning):
+ pass
+
+
+def listen(addr, family=socket.AF_INET, backlog=50, reuse_addr=True, reuse_port=None):
+ """Convenience function for opening server sockets. This
+ socket can be used in :func:`~eventlet.serve` or a custom ``accept()`` loop.
+
+ Sets SO_REUSEADDR on the socket to save on annoyance.
+
+ :param addr: Address to listen on. For TCP sockets, this is a (host, port) tuple.
+ :param family: Socket family, optional. See :mod:`socket` documentation for available families.
+ :param backlog:
+
+ The maximum number of queued connections. Should be at least 1; the maximum
+ value is system-dependent.
+
+ :return: The listening green socket object.
+ """
+ sock = socket.socket(family, socket.SOCK_STREAM)
+ if reuse_addr and sys.platform[:3] != 'win':
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ if family in (socket.AF_INET, socket.AF_INET6) and addr[1] == 0:
+ if reuse_port:
+ warnings.warn(
+ '''listen on random port (0) with SO_REUSEPORT is dangerous.
+ Double check your intent.
+ Example problem: https://github.com/eventlet/eventlet/issues/411''',
+ ReuseRandomPortWarning, stacklevel=3)
+ elif reuse_port is None:
+ reuse_port = True
+ if reuse_port and hasattr(socket, 'SO_REUSEPORT'):
+ # NOTE(zhengwei): linux kernel >= 3.9
+ try:
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
+ # OSError is enough on Python 3+
+ except (OSError, socket.error) as ex:
+ if support.get_errno(ex) in (22, 92):
+ # A famous platform defines unsupported socket option.
+ # https://github.com/eventlet/eventlet/issues/380
+ # https://github.com/eventlet/eventlet/issues/418
+ warnings.warn(
+ '''socket.SO_REUSEPORT is defined but not supported.
+ On Windows: known bug, wontfix.
+ On other systems: please comment in the issue linked below.
+ More information: https://github.com/eventlet/eventlet/issues/380''',
+ ReusePortUnavailableWarning, stacklevel=3)
+
+ sock.bind(addr)
+ sock.listen(backlog)
+ return sock
+
+
+class StopServe(Exception):
+ """Exception class used for quitting :func:`~eventlet.serve` gracefully."""
+ pass
+
+
+def _stop_checker(t, server_gt, conn):
+ try:
+ try:
+ t.wait()
+ finally:
+ conn.close()
+ except greenlet.GreenletExit:
+ pass
+ except Exception:
+ greenthread.kill(server_gt, *sys.exc_info())
+
+
+def serve(sock, handle, concurrency=1000):
+ """Runs a server on the supplied socket. Calls the function *handle* in a
+ separate greenthread for every incoming client connection. *handle* takes
+ two arguments: the client socket object, and the client address::
+
+ def myhandle(client_sock, client_addr):
+ print("client connected", client_addr)
+
+ eventlet.serve(eventlet.listen(('127.0.0.1', 9999)), myhandle)
+
+ Returning from *handle* closes the client socket.
+
+ :func:`serve` blocks the calling greenthread; it won't return until
+ the server completes. If you desire an immediate return,
+ spawn a new greenthread for :func:`serve`.
+
+ Any uncaught exceptions raised in *handle* are raised as exceptions
+ from :func:`serve`, terminating the server, so be sure to be aware of the
+ exceptions your application can raise. The return value of *handle* is
+ ignored.
+
+ Raise a :class:`~eventlet.StopServe` exception to gracefully terminate the
+ server -- that's the only way to get the server() function to return rather
+ than raise.
+
+ The value in *concurrency* controls the maximum number of
+ greenthreads that will be open at any time handling requests. When
+ the server hits the concurrency limit, it stops accepting new
+ connections until the existing ones complete.
+ """
+ pool = greenpool.GreenPool(concurrency)
+ server_gt = greenthread.getcurrent()
+
+ while True:
+ try:
+ conn, addr = sock.accept()
+ gt = pool.spawn(handle, conn, addr)
+ gt.link(_stop_checker, server_gt, conn)
+ conn, addr, gt = None, None, None
+ except StopServe:
+ return
+
+
+def wrap_ssl(sock, *a, **kw):
+ """Convenience function for converting a regular socket into an
+ SSL socket. Has the same interface as :func:`ssl.wrap_socket`,
+ but can also use PyOpenSSL. Though, note that it ignores the
+ `cert_reqs`, `ssl_version`, `ca_certs`, `do_handshake_on_connect`,
+ and `suppress_ragged_eofs` arguments when using PyOpenSSL.
+
+ The preferred idiom is to call wrap_ssl directly on the creation
+ method, e.g., ``wrap_ssl(connect(addr))`` or
+ ``wrap_ssl(listen(addr), server_side=True)``. This way there is
+ no "naked" socket sitting around to accidentally corrupt the SSL
+ session.
+
+ :return Green SSL object.
+ """
+ return wrap_ssl_impl(sock, *a, **kw)
+
+
+try:
+ from eventlet.green import ssl
+ wrap_ssl_impl = ssl.wrap_socket
+except ImportError:
+ # trying PyOpenSSL
+ try:
+ from eventlet.green.OpenSSL import SSL
+ except ImportError:
+ def wrap_ssl_impl(*a, **kw):
+ raise ImportError(
+ "To use SSL with Eventlet, you must install PyOpenSSL or use Python 2.7 or later.")
+ else:
+ def wrap_ssl_impl(sock, keyfile=None, certfile=None, server_side=False,
+ cert_reqs=None, ssl_version=None, ca_certs=None,
+ do_handshake_on_connect=True,
+ suppress_ragged_eofs=True, ciphers=None):
+ # theoretically the ssl_version could be respected in this line
+ context = SSL.Context(SSL.SSLv23_METHOD)
+ if certfile is not None:
+ context.use_certificate_file(certfile)
+ if keyfile is not None:
+ context.use_privatekey_file(keyfile)
+ context.set_verify(SSL.VERIFY_NONE, lambda *x: True)
+
+ connection = SSL.Connection(context, sock)
+ if server_side:
+ connection.set_accept_state()
+ else:
+ connection.set_connect_state()
+ return connection
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/corolocal.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/corolocal.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a1a8dfa23d62f4ec696897f88b186e9136c62e9
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/corolocal.py
@@ -0,0 +1,53 @@
+import weakref
+
+from eventlet import greenthread
+
+__all__ = ['get_ident', 'local']
+
+
+def get_ident():
+ """ Returns ``id()`` of current greenlet. Useful for debugging."""
+ return id(greenthread.getcurrent())
+
+
+# the entire purpose of this class is to store off the constructor
+# arguments in a local variable without calling __init__ directly
+class _localbase(object):
+ __slots__ = '_local__args', '_local__greens'
+
+ def __new__(cls, *args, **kw):
+ self = object.__new__(cls)
+ object.__setattr__(self, '_local__args', (args, kw))
+ object.__setattr__(self, '_local__greens', weakref.WeakKeyDictionary())
+ if (args or kw) and (cls.__init__ is object.__init__):
+ raise TypeError("Initialization arguments are not supported")
+ return self
+
+
+def _patch(thrl):
+ greens = object.__getattribute__(thrl, '_local__greens')
+ # until we can store the localdict on greenlets themselves,
+ # we store it in _local__greens on the local object
+ cur = greenthread.getcurrent()
+ if cur not in greens:
+ # must be the first time we've seen this greenlet, call __init__
+ greens[cur] = {}
+ cls = type(thrl)
+ if cls.__init__ is not object.__init__:
+ args, kw = object.__getattribute__(thrl, '_local__args')
+ thrl.__init__(*args, **kw)
+ object.__setattr__(thrl, '__dict__', greens[cur])
+
+
+class local(_localbase):
+ def __getattribute__(self, attr):
+ _patch(self)
+ return object.__getattribute__(self, attr)
+
+ def __setattr__(self, attr, value):
+ _patch(self)
+ return object.__setattr__(self, attr, value)
+
+ def __delattr__(self, attr):
+ _patch(self)
+ return object.__delattr__(self, attr)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/coros.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/coros.py
new file mode 100644
index 0000000000000000000000000000000000000000..431e6f0576759238759f2b2662e06528dd6bfabc
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/coros.py
@@ -0,0 +1,61 @@
+from __future__ import print_function
+
+from eventlet import event as _event
+
+
+class metaphore(object):
+ """This is sort of an inverse semaphore: a counter that starts at 0 and
+ waits only if nonzero. It's used to implement a "wait for all" scenario.
+
+ >>> from eventlet import coros, spawn_n
+ >>> count = coros.metaphore()
+ >>> count.wait()
+ >>> def decrementer(count, id):
+ ... print("{0} decrementing".format(id))
+ ... count.dec()
+ ...
+ >>> _ = spawn_n(decrementer, count, 'A')
+ >>> _ = spawn_n(decrementer, count, 'B')
+ >>> count.inc(2)
+ >>> count.wait()
+ A decrementing
+ B decrementing
+ """
+
+ def __init__(self):
+ self.counter = 0
+ self.event = _event.Event()
+ # send() right away, else we'd wait on the default 0 count!
+ self.event.send()
+
+ def inc(self, by=1):
+ """Increment our counter. If this transitions the counter from zero to
+ nonzero, make any subsequent :meth:`wait` call wait.
+ """
+ assert by > 0
+ self.counter += by
+ if self.counter == by:
+ # If we just incremented self.counter by 'by', and the new count
+ # equals 'by', then the old value of self.counter was 0.
+ # Transitioning from 0 to a nonzero value means wait() must
+ # actually wait.
+ self.event.reset()
+
+ def dec(self, by=1):
+ """Decrement our counter. If this transitions the counter from nonzero
+ to zero, a current or subsequent wait() call need no longer wait.
+ """
+ assert by > 0
+ self.counter -= by
+ if self.counter <= 0:
+ # Don't leave self.counter < 0, that will screw things up in
+ # future calls.
+ self.counter = 0
+ # Transitioning from nonzero to 0 means wait() need no longer wait.
+ self.event.send()
+
+ def wait(self):
+ """Suspend the caller only if our count is nonzero. In that case,
+ resume the caller once the count decrements to zero again.
+ """
+ self.event.wait()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/dagpool.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/dagpool.py
new file mode 100644
index 0000000000000000000000000000000000000000..68bb49a68e0e0ffff30da2b3c0e37cb9451c1f20
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/dagpool.py
@@ -0,0 +1,602 @@
+# @file dagpool.py
+# @author Nat Goodspeed
+# @date 2016-08-08
+# @brief Provide DAGPool class
+
+from eventlet.event import Event
+from eventlet import greenthread
+import six
+import collections
+
+
+# value distinguished from any other Python value including None
+_MISSING = object()
+
+
+class Collision(Exception):
+ """
+ DAGPool raises Collision when you try to launch two greenthreads with the
+ same key, or post() a result for a key corresponding to a greenthread, or
+ post() twice for the same key. As with KeyError, str(collision) names the
+ key in question.
+ """
+ pass
+
+
+class PropagateError(Exception):
+ """
+ When a DAGPool greenthread terminates with an exception instead of
+ returning a result, attempting to retrieve its value raises
+ PropagateError.
+
+ Attributes:
+
+ key
+ the key of the greenthread which raised the exception
+
+ exc
+ the exception object raised by the greenthread
+ """
+ def __init__(self, key, exc):
+ # initialize base class with a reasonable string message
+ msg = "PropagateError({0}): {1}: {2}" \
+ .format(key, exc.__class__.__name__, exc)
+ super(PropagateError, self).__init__(msg)
+ self.msg = msg
+ # Unless we set args, this is unpickleable:
+ # https://bugs.python.org/issue1692335
+ self.args = (key, exc)
+ self.key = key
+ self.exc = exc
+
+ def __str__(self):
+ return self.msg
+
+
+class DAGPool(object):
+ """
+ A DAGPool is a pool that constrains greenthreads, not by max concurrency,
+ but by data dependencies.
+
+ This is a way to implement general DAG dependencies. A simple dependency
+ tree (flowing in either direction) can straightforwardly be implemented
+ using recursion and (e.g.)
+ :meth:`GreenThread.imap() `.
+ What gets complicated is when a given node depends on several other nodes
+ as well as contributing to several other nodes.
+
+ With DAGPool, you concurrently launch all applicable greenthreads; each
+ will proceed as soon as it has all required inputs. The DAG is implicit in
+ which items are required by each greenthread.
+
+ Each greenthread is launched in a DAGPool with a key: any value that can
+ serve as a Python dict key. The caller also specifies an iterable of other
+ keys on which this greenthread depends. This iterable may be empty.
+
+ The greenthread callable must accept (key, results), where:
+
+ key
+ is its own key
+
+ results
+ is an iterable of (key, value) pairs.
+
+ A newly-launched DAGPool greenthread is entered immediately, and can
+ perform any necessary setup work. At some point it will iterate over the
+ (key, value) pairs from the passed 'results' iterable. Doing so blocks the
+ greenthread until a value is available for each of the keys specified in
+ its initial dependencies iterable. These (key, value) pairs are delivered
+ in chronological order, *not* the order in which they are initially
+ specified: each value will be delivered as soon as it becomes available.
+
+ The value returned by a DAGPool greenthread becomes the value for its
+ key, which unblocks any other greenthreads waiting on that key.
+
+ If a DAGPool greenthread terminates with an exception instead of returning
+ a value, attempting to retrieve the value raises :class:`PropagateError`,
+ which binds the key of the original greenthread and the original
+ exception. Unless the greenthread attempting to retrieve the value handles
+ PropagateError, that exception will in turn be wrapped in a PropagateError
+ of its own, and so forth. The code that ultimately handles PropagateError
+ can follow the chain of PropagateError.exc attributes to discover the flow
+ of that exception through the DAG of greenthreads.
+
+ External greenthreads may also interact with a DAGPool. See :meth:`wait_each`,
+ :meth:`waitall`, :meth:`post`.
+
+ It is not recommended to constrain external DAGPool producer greenthreads
+ in a :class:`GreenPool `: it may be hard to
+ provably avoid deadlock.
+
+ .. automethod:: __init__
+ .. automethod:: __getitem__
+ """
+
+ _Coro = collections.namedtuple("_Coro", ("greenthread", "pending"))
+
+ def __init__(self, preload={}):
+ """
+ DAGPool can be prepopulated with an initial dict or iterable of (key,
+ value) pairs. These (key, value) pairs are of course immediately
+ available for any greenthread that depends on any of those keys.
+ """
+ try:
+ # If a dict is passed, copy it. Don't risk a subsequent
+ # modification to passed dict affecting our internal state.
+ iteritems = six.iteritems(preload)
+ except AttributeError:
+ # Not a dict, just an iterable of (key, value) pairs
+ iteritems = preload
+
+ # Load the initial dict
+ self.values = dict(iteritems)
+
+ # track greenthreads
+ self.coros = {}
+
+ # The key to blocking greenthreads is the Event.
+ self.event = Event()
+
+ def waitall(self):
+ """
+ waitall() blocks the calling greenthread until there is a value for
+ every DAGPool greenthread launched by :meth:`spawn`. It returns a dict
+ containing all :class:`preload data `, all data from
+ :meth:`post` and all values returned by spawned greenthreads.
+
+ See also :meth:`wait`.
+ """
+ # waitall() is an alias for compatibility with GreenPool
+ return self.wait()
+
+ def wait(self, keys=_MISSING):
+ """
+ *keys* is an optional iterable of keys. If you omit the argument, it
+ waits for all the keys from :class:`preload data `, from
+ :meth:`post` calls and from :meth:`spawn` calls: in other words, all
+ the keys of which this DAGPool is aware.
+
+ wait() blocks the calling greenthread until all of the relevant keys
+ have values. wait() returns a dict whose keys are the relevant keys,
+ and whose values come from the *preload* data, from values returned by
+ DAGPool greenthreads or from :meth:`post` calls.
+
+ If a DAGPool greenthread terminates with an exception, wait() will
+ raise :class:`PropagateError` wrapping that exception. If more than
+ one greenthread terminates with an exception, it is indeterminate
+ which one wait() will raise.
+
+ If an external greenthread posts a :class:`PropagateError` instance,
+ wait() will raise that PropagateError. If more than one greenthread
+ posts PropagateError, it is indeterminate which one wait() will raise.
+
+ See also :meth:`wait_each_success`, :meth:`wait_each_exception`.
+ """
+ # This is mostly redundant with wait_each() functionality.
+ return dict(self.wait_each(keys))
+
+ def wait_each(self, keys=_MISSING):
+ """
+ *keys* is an optional iterable of keys. If you omit the argument, it
+ waits for all the keys from :class:`preload data `, from
+ :meth:`post` calls and from :meth:`spawn` calls: in other words, all
+ the keys of which this DAGPool is aware.
+
+ wait_each() is a generator producing (key, value) pairs as a value
+ becomes available for each requested key. wait_each() blocks the
+ calling greenthread until the next value becomes available. If the
+ DAGPool was prepopulated with values for any of the relevant keys, of
+ course those can be delivered immediately without waiting.
+
+ Delivery order is intentionally decoupled from the initial sequence of
+ keys: each value is delivered as soon as it becomes available. If
+ multiple keys are available at the same time, wait_each() delivers
+ each of the ready ones in arbitrary order before blocking again.
+
+ The DAGPool does not distinguish between a value returned by one of
+ its own greenthreads and one provided by a :meth:`post` call or *preload* data.
+
+ The wait_each() generator terminates (raises StopIteration) when all
+ specified keys have been delivered. Thus, typical usage might be:
+
+ ::
+
+ for key, value in dagpool.wait_each(keys):
+ # process this ready key and value
+ # continue processing now that we've gotten values for all keys
+
+ By implication, if you pass wait_each() an empty iterable of keys, it
+ returns immediately without yielding anything.
+
+ If the value to be delivered is a :class:`PropagateError` exception object, the
+ generator raises that PropagateError instead of yielding it.
+
+ See also :meth:`wait_each_success`, :meth:`wait_each_exception`.
+ """
+ # Build a local set() and then call _wait_each().
+ return self._wait_each(self._get_keyset_for_wait_each(keys))
+
+ def wait_each_success(self, keys=_MISSING):
+ """
+ wait_each_success() filters results so that only success values are
+ yielded. In other words, unlike :meth:`wait_each`, wait_each_success()
+ will not raise :class:`PropagateError`. Not every provided (or
+ defaulted) key will necessarily be represented, though naturally the
+ generator will not finish until all have completed.
+
+ In all other respects, wait_each_success() behaves like :meth:`wait_each`.
+ """
+ for key, value in self._wait_each_raw(self._get_keyset_for_wait_each(keys)):
+ if not isinstance(value, PropagateError):
+ yield key, value
+
+ def wait_each_exception(self, keys=_MISSING):
+ """
+ wait_each_exception() filters results so that only exceptions are
+ yielded. Not every provided (or defaulted) key will necessarily be
+ represented, though naturally the generator will not finish until
+ all have completed.
+
+ Unlike other DAGPool methods, wait_each_exception() simply yields
+ :class:`PropagateError` instances as values rather than raising them.
+
+ In all other respects, wait_each_exception() behaves like :meth:`wait_each`.
+ """
+ for key, value in self._wait_each_raw(self._get_keyset_for_wait_each(keys)):
+ if isinstance(value, PropagateError):
+ yield key, value
+
+ def _get_keyset_for_wait_each(self, keys):
+ """
+ wait_each(), wait_each_success() and wait_each_exception() promise
+ that if you pass an iterable of keys, the method will wait for results
+ from those keys -- but if you omit the keys argument, the method will
+ wait for results from all known keys. This helper implements that
+ distinction, returning a set() of the relevant keys.
+ """
+ if keys is not _MISSING:
+ return set(keys)
+ else:
+ # keys arg omitted -- use all the keys we know about
+ return set(six.iterkeys(self.coros)) | set(six.iterkeys(self.values))
+
+ def _wait_each(self, pending):
+ """
+ When _wait_each() encounters a value of PropagateError, it raises it.
+
+ In all other respects, _wait_each() behaves like _wait_each_raw().
+ """
+ for key, value in self._wait_each_raw(pending):
+ yield key, self._value_or_raise(value)
+
+ @staticmethod
+ def _value_or_raise(value):
+ # Most methods attempting to deliver PropagateError should raise that
+ # instead of simply returning it.
+ if isinstance(value, PropagateError):
+ raise value
+ return value
+
+ def _wait_each_raw(self, pending):
+ """
+ pending is a set() of keys for which we intend to wait. THIS SET WILL
+ BE DESTRUCTIVELY MODIFIED: as each key acquires a value, that key will
+ be removed from the passed 'pending' set.
+
+ _wait_each_raw() does not treat a PropagateError instance specially:
+ it will be yielded to the caller like any other value.
+
+ In all other respects, _wait_each_raw() behaves like wait_each().
+ """
+ while True:
+ # Before even waiting, show caller any (key, value) pairs that
+ # are already available. Copy 'pending' because we want to be able
+ # to remove items from the original set while iterating.
+ for key in pending.copy():
+ value = self.values.get(key, _MISSING)
+ if value is not _MISSING:
+ # found one, it's no longer pending
+ pending.remove(key)
+ yield (key, value)
+
+ if not pending:
+ # Once we've yielded all the caller's keys, done.
+ break
+
+ # There are still more keys pending, so wait.
+ self.event.wait()
+
+ def spawn(self, key, depends, function, *args, **kwds):
+ """
+ Launch the passed *function(key, results, ...)* as a greenthread,
+ passing it:
+
+ - the specified *key*
+ - an iterable of (key, value) pairs
+ - whatever other positional args or keywords you specify.
+
+ Iterating over the *results* iterable behaves like calling
+ :meth:`wait_each(depends) `.
+
+ Returning from *function()* behaves like
+ :meth:`post(key, return_value) `.
+
+ If *function()* terminates with an exception, that exception is wrapped
+ in :class:`PropagateError` with the greenthread's *key* and (effectively) posted
+ as the value for that key. Attempting to retrieve that value will
+ raise that PropagateError.
+
+ Thus, if the greenthread with key 'a' terminates with an exception,
+ and greenthread 'b' depends on 'a', when greenthread 'b' attempts to
+ iterate through its *results* argument, it will encounter
+ PropagateError. So by default, an uncaught exception will propagate
+ through all the downstream dependencies.
+
+ If you pass :meth:`spawn` a key already passed to spawn() or :meth:`post`, spawn()
+ raises :class:`Collision`.
+ """
+ if key in self.coros or key in self.values:
+ raise Collision(key)
+
+ # The order is a bit tricky. First construct the set() of keys.
+ pending = set(depends)
+ # It's important that we pass to _wait_each() the same 'pending' set()
+ # that we store in self.coros for this key. The generator-iterator
+ # returned by _wait_each() becomes the function's 'results' iterable.
+ newcoro = greenthread.spawn(self._wrapper, function, key,
+ self._wait_each(pending),
+ *args, **kwds)
+ # Also capture the same (!) set in the new _Coro object for this key.
+ # We must be able to observe ready keys being removed from the set.
+ self.coros[key] = self._Coro(newcoro, pending)
+
+ def _wrapper(self, function, key, results, *args, **kwds):
+ """
+ This wrapper runs the top-level function in a DAGPool greenthread,
+ posting its return value (or PropagateError) to the DAGPool.
+ """
+ try:
+ # call our passed function
+ result = function(key, results, *args, **kwds)
+ except Exception as err:
+ # Wrap any exception it may raise in a PropagateError.
+ result = PropagateError(key, err)
+ finally:
+ # function() has returned (or terminated with an exception). We no
+ # longer need to track this greenthread in self.coros. Remove it
+ # first so post() won't complain about a running greenthread.
+ del self.coros[key]
+
+ try:
+ # as advertised, try to post() our return value
+ self.post(key, result)
+ except Collision:
+ # if we've already post()ed a result, oh well
+ pass
+
+ # also, in case anyone cares...
+ return result
+
+ def spawn_many(self, depends, function, *args, **kwds):
+ """
+ spawn_many() accepts a single *function* whose parameters are the same
+ as for :meth:`spawn`.
+
+ The difference is that spawn_many() accepts a dependency dict
+ *depends*. A new greenthread is spawned for each key in the dict. That
+ dict key's value should be an iterable of other keys on which this
+ greenthread depends.
+
+ If the *depends* dict contains any key already passed to :meth:`spawn`
+ or :meth:`post`, spawn_many() raises :class:`Collision`. It is
+ indeterminate how many of the other keys in *depends* will have
+ successfully spawned greenthreads.
+ """
+ # Iterate over 'depends' items, relying on self.spawn() not to
+ # context-switch so no one can modify 'depends' along the way.
+ for key, deps in six.iteritems(depends):
+ self.spawn(key, deps, function, *args, **kwds)
+
+ def kill(self, key):
+ """
+ Kill the greenthread that was spawned with the specified *key*.
+
+ If no such greenthread was spawned, raise KeyError.
+ """
+ # let KeyError, if any, propagate
+ self.coros[key].greenthread.kill()
+ # once killed, remove it
+ del self.coros[key]
+
+ def post(self, key, value, replace=False):
+ """
+ post(key, value) stores the passed *value* for the passed *key*. It
+ then causes each greenthread blocked on its results iterable, or on
+ :meth:`wait_each(keys) `, to check for new values.
+ A waiting greenthread might not literally resume on every single
+ post() of a relevant key, but the first post() of a relevant key
+ ensures that it will resume eventually, and when it does it will catch
+ up with all relevant post() calls.
+
+ Calling post(key, value) when there is a running greenthread with that
+ same *key* raises :class:`Collision`. If you must post(key, value) instead of
+ letting the greenthread run to completion, you must first call
+ :meth:`kill(key) `.
+
+ The DAGPool implicitly post()s the return value from each of its
+ greenthreads. But a greenthread may explicitly post() a value for its
+ own key, which will cause its return value to be discarded.
+
+ Calling post(key, value, replace=False) (the default *replace*) when a
+ value for that key has already been posted, by any means, raises
+ :class:`Collision`.
+
+ Calling post(key, value, replace=True) when a value for that key has
+ already been posted, by any means, replaces the previously-stored
+ value. However, that may make it complicated to reason about the
+ behavior of greenthreads waiting on that key.
+
+ After a post(key, value1) followed by post(key, value2, replace=True),
+ it is unspecified which pending :meth:`wait_each([key...]) `
+ calls (or greenthreads iterating over *results* involving that key)
+ will observe *value1* versus *value2*. It is guaranteed that
+ subsequent wait_each([key...]) calls (or greenthreads spawned after
+ that point) will observe *value2*.
+
+ A successful call to
+ post(key, :class:`PropagateError(key, ExceptionSubclass) `)
+ ensures that any subsequent attempt to retrieve that key's value will
+ raise that PropagateError instance.
+ """
+ # First, check if we're trying to post() to a key with a running
+ # greenthread.
+ # A DAGPool greenthread is explicitly permitted to post() to its
+ # OWN key.
+ coro = self.coros.get(key, _MISSING)
+ if coro is not _MISSING and coro.greenthread is not greenthread.getcurrent():
+ # oh oh, trying to post a value for running greenthread from
+ # some other greenthread
+ raise Collision(key)
+
+ # Here, either we're posting a value for a key with no greenthread or
+ # we're posting from that greenthread itself.
+
+ # Has somebody already post()ed a value for this key?
+ # Unless replace == True, this is a problem.
+ if key in self.values and not replace:
+ raise Collision(key)
+
+ # Either we've never before posted a value for this key, or we're
+ # posting with replace == True.
+
+ # update our database
+ self.values[key] = value
+ # and wake up pending waiters
+ self.event.send()
+ # The comment in Event.reset() says: "it's better to create a new
+ # event rather than reset an old one". Okay, fine. We do want to be
+ # able to support new waiters, so create a new Event.
+ self.event = Event()
+
+ def __getitem__(self, key):
+ """
+ __getitem__(key) (aka dagpool[key]) blocks until *key* has a value,
+ then delivers that value.
+ """
+ # This is a degenerate case of wait_each(). Construct a tuple
+ # containing only this 'key'. wait_each() will yield exactly one (key,
+ # value) pair. Return just its value.
+ for _, value in self.wait_each((key,)):
+ return value
+
+ def get(self, key, default=None):
+ """
+ get() returns the value for *key*. If *key* does not yet have a value,
+ get() returns *default*.
+ """
+ return self._value_or_raise(self.values.get(key, default))
+
+ def keys(self):
+ """
+ Return a snapshot tuple of keys for which we currently have values.
+ """
+ # Explicitly return a copy rather than an iterator: don't assume our
+ # caller will finish iterating before new values are posted.
+ return tuple(six.iterkeys(self.values))
+
+ def items(self):
+ """
+ Return a snapshot tuple of currently-available (key, value) pairs.
+ """
+ # Don't assume our caller will finish iterating before new values are
+ # posted.
+ return tuple((key, self._value_or_raise(value))
+ for key, value in six.iteritems(self.values))
+
+ def running(self):
+ """
+ Return number of running DAGPool greenthreads. This includes
+ greenthreads blocked while iterating through their *results* iterable,
+ that is, greenthreads waiting on values from other keys.
+ """
+ return len(self.coros)
+
+ def running_keys(self):
+ """
+ Return keys for running DAGPool greenthreads. This includes
+ greenthreads blocked while iterating through their *results* iterable,
+ that is, greenthreads waiting on values from other keys.
+ """
+ # return snapshot; don't assume caller will finish iterating before we
+ # next modify self.coros
+ return tuple(six.iterkeys(self.coros))
+
+ def waiting(self):
+ """
+ Return number of waiting DAGPool greenthreads, that is, greenthreads
+ still waiting on values from other keys. This explicitly does *not*
+ include external greenthreads waiting on :meth:`wait`,
+ :meth:`waitall`, :meth:`wait_each`.
+ """
+ # n.b. if Event would provide a count of its waiters, we could say
+ # something about external greenthreads as well.
+ # The logic to determine this count is exactly the same as the general
+ # waiting_for() call.
+ return len(self.waiting_for())
+
+ # Use _MISSING instead of None as the default 'key' param so we can permit
+ # None as a supported key.
+ def waiting_for(self, key=_MISSING):
+ """
+ waiting_for(key) returns a set() of the keys for which the DAGPool
+ greenthread spawned with that *key* is still waiting. If you pass a
+ *key* for which no greenthread was spawned, waiting_for() raises
+ KeyError.
+
+ waiting_for() without argument returns a dict. Its keys are the keys
+ of DAGPool greenthreads still waiting on one or more values. In the
+ returned dict, the value of each such key is the set of other keys for
+ which that greenthread is still waiting.
+
+ This method allows diagnosing a "hung" DAGPool. If certain
+ greenthreads are making no progress, it's possible that they are
+ waiting on keys for which there is no greenthread and no :meth:`post` data.
+ """
+ # We may have greenthreads whose 'pending' entry indicates they're
+ # waiting on some keys even though values have now been posted for
+ # some or all of those keys, because those greenthreads have not yet
+ # regained control since values were posted. So make a point of
+ # excluding values that are now available.
+ available = set(six.iterkeys(self.values))
+
+ if key is not _MISSING:
+ # waiting_for(key) is semantically different than waiting_for().
+ # It's just that they both seem to want the same method name.
+ coro = self.coros.get(key, _MISSING)
+ if coro is _MISSING:
+ # Hmm, no running greenthread with this key. But was there
+ # EVER a greenthread with this key? If not, let KeyError
+ # propagate.
+ self.values[key]
+ # Oh good, there's a value for this key. Either the
+ # greenthread finished, or somebody posted a value. Just say
+ # the greenthread isn't waiting for anything.
+ return set()
+ else:
+ # coro is the _Coro for the running greenthread with the
+ # specified key.
+ return coro.pending - available
+
+ # This is a waiting_for() call, i.e. a general query rather than for a
+ # specific key.
+
+ # Start by iterating over (key, coro) pairs in self.coros. Generate
+ # (key, pending) pairs in which 'pending' is the set of keys on which
+ # the greenthread believes it's waiting, minus the set of keys that
+ # are now available. Filter out any pair in which 'pending' is empty,
+ # that is, that greenthread will be unblocked next time it resumes.
+ # Make a dict from those pairs.
+ return dict((key, pending)
+ for key, pending in ((key, (coro.pending - available))
+ for key, coro in six.iteritems(self.coros))
+ if pending)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/db_pool.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/db_pool.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef74d99ce4a895278f9e541f0c2f7a9cb7a9aab4
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/db_pool.py
@@ -0,0 +1,463 @@
+from __future__ import print_function
+
+from collections import deque
+from contextlib import contextmanager
+import sys
+import time
+
+from eventlet.pools import Pool
+from eventlet import timeout
+from eventlet import hubs
+from eventlet.hubs.timer import Timer
+from eventlet.greenthread import GreenThread
+
+
+_MISSING = object()
+
+
+class ConnectTimeout(Exception):
+ pass
+
+
+def cleanup_rollback(conn):
+ conn.rollback()
+
+
+class BaseConnectionPool(Pool):
+ def __init__(self, db_module,
+ min_size=0, max_size=4,
+ max_idle=10, max_age=30,
+ connect_timeout=5,
+ cleanup=cleanup_rollback,
+ *args, **kwargs):
+ """
+ Constructs a pool with at least *min_size* connections and at most
+ *max_size* connections. Uses *db_module* to construct new connections.
+
+ The *max_idle* parameter determines how long pooled connections can
+ remain idle, in seconds. After *max_idle* seconds have elapsed
+ without the connection being used, the pool closes the connection.
+
+ *max_age* is how long any particular connection is allowed to live.
+ Connections that have been open for longer than *max_age* seconds are
+ closed, regardless of idle time. If *max_age* is 0, all connections are
+ closed on return to the pool, reducing it to a concurrency limiter.
+
+ *connect_timeout* is the duration in seconds that the pool will wait
+ before timing out on connect() to the database. If triggered, the
+ timeout will raise a ConnectTimeout from get().
+
+ The remainder of the arguments are used as parameters to the
+ *db_module*'s connection constructor.
+ """
+ assert(db_module)
+ self._db_module = db_module
+ self._args = args
+ self._kwargs = kwargs
+ self.max_idle = max_idle
+ self.max_age = max_age
+ self.connect_timeout = connect_timeout
+ self._expiration_timer = None
+ self.cleanup = cleanup
+ super(BaseConnectionPool, self).__init__(min_size=min_size,
+ max_size=max_size,
+ order_as_stack=True)
+
+ def _schedule_expiration(self):
+ """Sets up a timer that will call _expire_old_connections when the
+ oldest connection currently in the free pool is ready to expire. This
+ is the earliest possible time that a connection could expire, thus, the
+ timer will be running as infrequently as possible without missing a
+ possible expiration.
+
+ If this function is called when a timer is already scheduled, it does
+ nothing.
+
+ If max_age or max_idle is 0, _schedule_expiration likewise does nothing.
+ """
+ if self.max_age == 0 or self.max_idle == 0:
+ # expiration is unnecessary because all connections will be expired
+ # on put
+ return
+
+ if (self._expiration_timer is not None
+ and not getattr(self._expiration_timer, 'called', False)):
+ # the next timer is already scheduled
+ return
+
+ try:
+ now = time.time()
+ self._expire_old_connections(now)
+ # the last item in the list, because of the stack ordering,
+ # is going to be the most-idle
+ idle_delay = (self.free_items[-1][0] - now) + self.max_idle
+ oldest = min([t[1] for t in self.free_items])
+ age_delay = (oldest - now) + self.max_age
+
+ next_delay = min(idle_delay, age_delay)
+ except (IndexError, ValueError):
+ # no free items, unschedule ourselves
+ self._expiration_timer = None
+ return
+
+ if next_delay > 0:
+ # set up a continuous self-calling loop
+ self._expiration_timer = Timer(next_delay, GreenThread(hubs.get_hub().greenlet).switch,
+ self._schedule_expiration, [], {})
+ self._expiration_timer.schedule()
+
+ def _expire_old_connections(self, now):
+ """Iterates through the open connections contained in the pool, closing
+ ones that have remained idle for longer than max_idle seconds, or have
+ been in existence for longer than max_age seconds.
+
+ *now* is the current time, as returned by time.time().
+ """
+ original_count = len(self.free_items)
+ expired = [
+ conn
+ for last_used, created_at, conn in self.free_items
+ if self._is_expired(now, last_used, created_at)]
+
+ new_free = [
+ (last_used, created_at, conn)
+ for last_used, created_at, conn in self.free_items
+ if not self._is_expired(now, last_used, created_at)]
+ self.free_items.clear()
+ self.free_items.extend(new_free)
+
+ # adjust the current size counter to account for expired
+ # connections
+ self.current_size -= original_count - len(self.free_items)
+
+ for conn in expired:
+ self._safe_close(conn, quiet=True)
+
+ def _is_expired(self, now, last_used, created_at):
+ """Returns true and closes the connection if it's expired.
+ """
+ if (self.max_idle <= 0 or self.max_age <= 0
+ or now - last_used > self.max_idle
+ or now - created_at > self.max_age):
+ return True
+ return False
+
+ def _unwrap_connection(self, conn):
+ """If the connection was wrapped by a subclass of
+ BaseConnectionWrapper and is still functional (as determined
+ by the __nonzero__, or __bool__ in python3, method), returns
+ the unwrapped connection. If anything goes wrong with this
+ process, returns None.
+ """
+ base = None
+ try:
+ if conn:
+ base = conn._base
+ conn._destroy()
+ else:
+ base = None
+ except AttributeError:
+ pass
+ return base
+
+ def _safe_close(self, conn, quiet=False):
+ """Closes the (already unwrapped) connection, squelching any
+ exceptions.
+ """
+ try:
+ conn.close()
+ except AttributeError:
+ pass # conn is None, or junk
+ except Exception:
+ if not quiet:
+ print("Connection.close raised: %s" % (sys.exc_info()[1]))
+
+ def get(self):
+ conn = super(BaseConnectionPool, self).get()
+
+ # None is a flag value that means that put got called with
+ # something it couldn't use
+ if conn is None:
+ try:
+ conn = self.create()
+ except Exception:
+ # unconditionally increase the free pool because
+ # even if there are waiters, doing a full put
+ # would incur a greenlib switch and thus lose the
+ # exception stack
+ self.current_size -= 1
+ raise
+
+ # if the call to get() draws from the free pool, it will come
+ # back as a tuple
+ if isinstance(conn, tuple):
+ _last_used, created_at, conn = conn
+ else:
+ created_at = time.time()
+
+ # wrap the connection so the consumer can call close() safely
+ wrapped = PooledConnectionWrapper(conn, self)
+ # annotating the wrapper so that when it gets put in the pool
+ # again, we'll know how old it is
+ wrapped._db_pool_created_at = created_at
+ return wrapped
+
+ def put(self, conn, cleanup=_MISSING):
+ created_at = getattr(conn, '_db_pool_created_at', 0)
+ now = time.time()
+ conn = self._unwrap_connection(conn)
+
+ if self._is_expired(now, now, created_at):
+ self._safe_close(conn, quiet=False)
+ conn = None
+ elif cleanup is not None:
+ if cleanup is _MISSING:
+ cleanup = self.cleanup
+ # by default, call rollback in case the connection is in the middle
+ # of a transaction. However, rollback has performance implications
+ # so optionally do nothing or call something else like ping
+ try:
+ if conn:
+ cleanup(conn)
+ except Exception as e:
+ # we don't care what the exception was, we just know the
+ # connection is dead
+ print("WARNING: cleanup %s raised: %s" % (cleanup, e))
+ conn = None
+ except:
+ conn = None
+ raise
+
+ if conn is not None:
+ super(BaseConnectionPool, self).put((now, created_at, conn))
+ else:
+ # wake up any waiters with a flag value that indicates
+ # they need to manufacture a connection
+ if self.waiting() > 0:
+ super(BaseConnectionPool, self).put(None)
+ else:
+ # no waiters -- just change the size
+ self.current_size -= 1
+ self._schedule_expiration()
+
+ @contextmanager
+ def item(self, cleanup=_MISSING):
+ conn = self.get()
+ try:
+ yield conn
+ finally:
+ self.put(conn, cleanup=cleanup)
+
+ def clear(self):
+ """Close all connections that this pool still holds a reference to,
+ and removes all references to them.
+ """
+ if self._expiration_timer:
+ self._expiration_timer.cancel()
+ free_items, self.free_items = self.free_items, deque()
+ for item in free_items:
+ # Free items created using min_size>0 are not tuples.
+ conn = item[2] if isinstance(item, tuple) else item
+ self._safe_close(conn, quiet=True)
+ self.current_size -= 1
+
+ def __del__(self):
+ self.clear()
+
+
+class TpooledConnectionPool(BaseConnectionPool):
+ """A pool which gives out :class:`~eventlet.tpool.Proxy`-based database
+ connections.
+ """
+
+ def create(self):
+ now = time.time()
+ return now, now, self.connect(
+ self._db_module, self.connect_timeout, *self._args, **self._kwargs)
+
+ @classmethod
+ def connect(cls, db_module, connect_timeout, *args, **kw):
+ t = timeout.Timeout(connect_timeout, ConnectTimeout())
+ try:
+ from eventlet import tpool
+ conn = tpool.execute(db_module.connect, *args, **kw)
+ return tpool.Proxy(conn, autowrap_names=('cursor',))
+ finally:
+ t.cancel()
+
+
+class RawConnectionPool(BaseConnectionPool):
+ """A pool which gives out plain database connections.
+ """
+
+ def create(self):
+ now = time.time()
+ return now, now, self.connect(
+ self._db_module, self.connect_timeout, *self._args, **self._kwargs)
+
+ @classmethod
+ def connect(cls, db_module, connect_timeout, *args, **kw):
+ t = timeout.Timeout(connect_timeout, ConnectTimeout())
+ try:
+ return db_module.connect(*args, **kw)
+ finally:
+ t.cancel()
+
+
+# default connection pool is the tpool one
+ConnectionPool = TpooledConnectionPool
+
+
+class GenericConnectionWrapper(object):
+ def __init__(self, baseconn):
+ self._base = baseconn
+
+ # Proxy all method calls to self._base
+ # FIXME: remove repetition; options to consider:
+ # * for name in (...):
+ # setattr(class, name, lambda self, *a, **kw: getattr(self._base, name)(*a, **kw))
+ # * def __getattr__(self, name): if name in (...): return getattr(self._base, name)
+ # * other?
+ def __enter__(self):
+ return self._base.__enter__()
+
+ def __exit__(self, exc, value, tb):
+ return self._base.__exit__(exc, value, tb)
+
+ def __repr__(self):
+ return self._base.__repr__()
+
+ _proxy_funcs = (
+ 'affected_rows',
+ 'autocommit',
+ 'begin',
+ 'change_user',
+ 'character_set_name',
+ 'close',
+ 'commit',
+ 'cursor',
+ 'dump_debug_info',
+ 'errno',
+ 'error',
+ 'errorhandler',
+ 'insert_id',
+ 'literal',
+ 'ping',
+ 'query',
+ 'rollback',
+ 'select_db',
+ 'server_capabilities',
+ 'set_character_set',
+ 'set_isolation_level',
+ 'set_server_option',
+ 'set_sql_mode',
+ 'show_warnings',
+ 'shutdown',
+ 'sqlstate',
+ 'stat',
+ 'store_result',
+ 'string_literal',
+ 'thread_id',
+ 'use_result',
+ 'warning_count',
+ )
+
+
+for _proxy_fun in GenericConnectionWrapper._proxy_funcs:
+ # excess wrapper for early binding (closure by value)
+ def _wrapper(_proxy_fun=_proxy_fun):
+ def _proxy_method(self, *args, **kwargs):
+ return getattr(self._base, _proxy_fun)(*args, **kwargs)
+ _proxy_method.func_name = _proxy_fun
+ _proxy_method.__name__ = _proxy_fun
+ _proxy_method.__qualname__ = 'GenericConnectionWrapper.' + _proxy_fun
+ return _proxy_method
+ setattr(GenericConnectionWrapper, _proxy_fun, _wrapper(_proxy_fun))
+del GenericConnectionWrapper._proxy_funcs
+del _proxy_fun
+del _wrapper
+
+
+class PooledConnectionWrapper(GenericConnectionWrapper):
+ """A connection wrapper where:
+ - the close method returns the connection to the pool instead of closing it directly
+ - ``bool(conn)`` returns a reasonable value
+ - returns itself to the pool if it gets garbage collected
+ """
+
+ def __init__(self, baseconn, pool):
+ super(PooledConnectionWrapper, self).__init__(baseconn)
+ self._pool = pool
+
+ def __nonzero__(self):
+ return (hasattr(self, '_base') and bool(self._base))
+
+ __bool__ = __nonzero__
+
+ def _destroy(self):
+ self._pool = None
+ try:
+ del self._base
+ except AttributeError:
+ pass
+
+ def close(self):
+ """Return the connection to the pool, and remove the
+ reference to it so that you can't use it again through this
+ wrapper object.
+ """
+ if self and self._pool:
+ self._pool.put(self)
+ self._destroy()
+
+ def __del__(self):
+ return # this causes some issues if __del__ is called in the
+ # main coroutine, so for now this is disabled
+ # self.close()
+
+
+class DatabaseConnector(object):
+ """
+ This is an object which will maintain a collection of database
+ connection pools on a per-host basis.
+ """
+
+ def __init__(self, module, credentials,
+ conn_pool=None, *args, **kwargs):
+ """constructor
+ *module*
+ Database module to use.
+ *credentials*
+ Mapping of hostname to connect arguments (e.g. username and password)
+ """
+ assert(module)
+ self._conn_pool_class = conn_pool
+ if self._conn_pool_class is None:
+ self._conn_pool_class = ConnectionPool
+ self._module = module
+ self._args = args
+ self._kwargs = kwargs
+ # this is a map of hostname to username/password
+ self._credentials = credentials
+ self._databases = {}
+
+ def credentials_for(self, host):
+ if host in self._credentials:
+ return self._credentials[host]
+ else:
+ return self._credentials.get('default', None)
+
+ def get(self, host, dbname):
+ """Returns a ConnectionPool to the target host and schema.
+ """
+ key = (host, dbname)
+ if key not in self._databases:
+ new_kwargs = self._kwargs.copy()
+ new_kwargs['db'] = dbname
+ new_kwargs['host'] = host
+ new_kwargs.update(self.credentials_for(host))
+ dbpool = self._conn_pool_class(
+ self._module, *self._args, **new_kwargs)
+ self._databases[key] = dbpool
+
+ return self._databases[key]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/debug.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/debug.py
new file mode 100644
index 0000000000000000000000000000000000000000..6481aeac9369bc73fe830ae75f3e79616491560e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/debug.py
@@ -0,0 +1,174 @@
+"""The debug module contains utilities and functions for better
+debugging Eventlet-powered applications."""
+from __future__ import print_function
+
+import os
+import sys
+import linecache
+import re
+import inspect
+
+__all__ = ['spew', 'unspew', 'format_hub_listeners', 'format_hub_timers',
+ 'hub_listener_stacks', 'hub_exceptions', 'tpool_exceptions',
+ 'hub_prevent_multiple_readers', 'hub_timer_stacks',
+ 'hub_blocking_detection']
+
+_token_splitter = re.compile('\W+')
+
+
+class Spew(object):
+
+ def __init__(self, trace_names=None, show_values=True):
+ self.trace_names = trace_names
+ self.show_values = show_values
+
+ def __call__(self, frame, event, arg):
+ if event == 'line':
+ lineno = frame.f_lineno
+ if '__file__' in frame.f_globals:
+ filename = frame.f_globals['__file__']
+ if (filename.endswith('.pyc') or
+ filename.endswith('.pyo')):
+ filename = filename[:-1]
+ name = frame.f_globals['__name__']
+ line = linecache.getline(filename, lineno)
+ else:
+ name = '[unknown]'
+ try:
+ src = inspect.getsourcelines(frame)
+ line = src[lineno]
+ except IOError:
+ line = 'Unknown code named [%s]. VM instruction #%d' % (
+ frame.f_code.co_name, frame.f_lasti)
+ if self.trace_names is None or name in self.trace_names:
+ print('%s:%s: %s' % (name, lineno, line.rstrip()))
+ if not self.show_values:
+ return self
+ details = []
+ tokens = _token_splitter.split(line)
+ for tok in tokens:
+ if tok in frame.f_globals:
+ details.append('%s=%r' % (tok, frame.f_globals[tok]))
+ if tok in frame.f_locals:
+ details.append('%s=%r' % (tok, frame.f_locals[tok]))
+ if details:
+ print("\t%s" % ' '.join(details))
+ return self
+
+
+def spew(trace_names=None, show_values=False):
+ """Install a trace hook which writes incredibly detailed logs
+ about what code is being executed to stdout.
+ """
+ sys.settrace(Spew(trace_names, show_values))
+
+
+def unspew():
+ """Remove the trace hook installed by spew.
+ """
+ sys.settrace(None)
+
+
+def format_hub_listeners():
+ """ Returns a formatted string of the current listeners on the current
+ hub. This can be useful in determining what's going on in the event system,
+ especially when used in conjunction with :func:`hub_listener_stacks`.
+ """
+ from eventlet import hubs
+ hub = hubs.get_hub()
+ result = ['READERS:']
+ for l in hub.get_readers():
+ result.append(repr(l))
+ result.append('WRITERS:')
+ for l in hub.get_writers():
+ result.append(repr(l))
+ return os.linesep.join(result)
+
+
+def format_hub_timers():
+ """ Returns a formatted string of the current timers on the current
+ hub. This can be useful in determining what's going on in the event system,
+ especially when used in conjunction with :func:`hub_timer_stacks`.
+ """
+ from eventlet import hubs
+ hub = hubs.get_hub()
+ result = ['TIMERS:']
+ for l in hub.timers:
+ result.append(repr(l))
+ return os.linesep.join(result)
+
+
+def hub_listener_stacks(state=False):
+ """Toggles whether or not the hub records the stack when clients register
+ listeners on file descriptors. This can be useful when trying to figure
+ out what the hub is up to at any given moment. To inspect the stacks
+ of the current listeners, call :func:`format_hub_listeners` at critical
+ junctures in the application logic.
+ """
+ from eventlet import hubs
+ hubs.get_hub().set_debug_listeners(state)
+
+
+def hub_timer_stacks(state=False):
+ """Toggles whether or not the hub records the stack when timers are set.
+ To inspect the stacks of the current timers, call :func:`format_hub_timers`
+ at critical junctures in the application logic.
+ """
+ from eventlet.hubs import timer
+ timer._g_debug = state
+
+
+def hub_prevent_multiple_readers(state=True):
+ """Toggle prevention of multiple greenlets reading from a socket
+
+ When multiple greenlets read from the same socket it is often hard
+ to predict which greenlet will receive what data. To achieve
+ resource sharing consider using ``eventlet.pools.Pool`` instead.
+
+ But if you really know what you are doing you can change the state
+ to ``False`` to stop the hub from protecting against this mistake.
+ """
+ from eventlet.hubs import hub
+ hub.g_prevent_multiple_readers = state
+
+
+def hub_exceptions(state=True):
+ """Toggles whether the hub prints exceptions that are raised from its
+ timers. This can be useful to see how greenthreads are terminating.
+ """
+ from eventlet import hubs
+ hubs.get_hub().set_timer_exceptions(state)
+ from eventlet import greenpool
+ greenpool.DEBUG = state
+
+
+def tpool_exceptions(state=False):
+ """Toggles whether tpool itself prints exceptions that are raised from
+ functions that are executed in it, in addition to raising them like
+ it normally does."""
+ from eventlet import tpool
+ tpool.QUIET = not state
+
+
+def hub_blocking_detection(state=False, resolution=1):
+ """Toggles whether Eventlet makes an effort to detect blocking
+ behavior in an application.
+
+ It does this by telling the kernel to raise a SIGALARM after a
+ short timeout, and clearing the timeout every time the hub
+ greenlet is resumed. Therefore, any code that runs for a long
+ time without yielding to the hub will get interrupted by the
+ blocking detector (don't use it in production!).
+
+ The *resolution* argument governs how long the SIGALARM timeout
+ waits in seconds. The implementation uses :func:`signal.setitimer`
+ and can be specified as a floating-point value.
+ The shorter the resolution, the greater the chance of false
+ positives.
+ """
+ from eventlet import hubs
+ assert resolution > 0
+ hubs.get_hub().debug_blocking = state
+ hubs.get_hub().debug_blocking_resolution = resolution
+ if not state:
+ hubs.get_hub().block_detect_post()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/event.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/event.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d99a544dcc4ebbe12a6c4cad9d87d2ce5d20066
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/event.py
@@ -0,0 +1,221 @@
+from __future__ import print_function
+
+from eventlet import hubs
+from eventlet.support import greenlets as greenlet
+
+__all__ = ['Event']
+
+
+class NOT_USED:
+ def __repr__(self):
+ return 'NOT_USED'
+
+
+NOT_USED = NOT_USED()
+
+
+class Event(object):
+ """An abstraction where an arbitrary number of coroutines
+ can wait for one event from another.
+
+ Events are similar to a Queue that can only hold one item, but differ
+ in two important ways:
+
+ 1. calling :meth:`send` never unschedules the current greenthread
+ 2. :meth:`send` can only be called once; create a new event to send again.
+
+ They are good for communicating results between coroutines, and
+ are the basis for how
+ :meth:`GreenThread.wait() `
+ is implemented.
+
+ >>> from eventlet import event
+ >>> import eventlet
+ >>> evt = event.Event()
+ >>> def baz(b):
+ ... evt.send(b + 1)
+ ...
+ >>> _ = eventlet.spawn_n(baz, 3)
+ >>> evt.wait()
+ 4
+ """
+ _result = None
+ _exc = None
+
+ def __init__(self):
+ self._waiters = set()
+ self.reset()
+
+ def __str__(self):
+ params = (self.__class__.__name__, hex(id(self)),
+ self._result, self._exc, len(self._waiters))
+ return '<%s at %s result=%r _exc=%r _waiters[%d]>' % params
+
+ def reset(self):
+ # this is kind of a misfeature and doesn't work perfectly well,
+ # it's better to create a new event rather than reset an old one
+ # removing documentation so that we don't get new use cases for it
+ assert self._result is not NOT_USED, 'Trying to re-reset() a fresh event.'
+ self._result = NOT_USED
+ self._exc = None
+
+ def ready(self):
+ """ Return true if the :meth:`wait` call will return immediately.
+ Used to avoid waiting for things that might take a while to time out.
+ For example, you can put a bunch of events into a list, and then visit
+ them all repeatedly, calling :meth:`ready` until one returns ``True``,
+ and then you can :meth:`wait` on that one."""
+ return self._result is not NOT_USED
+
+ def has_exception(self):
+ return self._exc is not None
+
+ def has_result(self):
+ return self._result is not NOT_USED and self._exc is None
+
+ def poll(self, notready=None):
+ if self.ready():
+ return self.wait()
+ return notready
+
+ # QQQ make it return tuple (type, value, tb) instead of raising
+ # because
+ # 1) "poll" does not imply raising
+ # 2) it's better not to screw up caller's sys.exc_info() by default
+ # (e.g. if caller wants to calls the function in except or finally)
+ def poll_exception(self, notready=None):
+ if self.has_exception():
+ return self.wait()
+ return notready
+
+ def poll_result(self, notready=None):
+ if self.has_result():
+ return self.wait()
+ return notready
+
+ def wait(self, timeout=None):
+ """Wait until another coroutine calls :meth:`send`.
+ Returns the value the other coroutine passed to :meth:`send`.
+
+ >>> import eventlet
+ >>> evt = eventlet.Event()
+ >>> def wait_on():
+ ... retval = evt.wait()
+ ... print("waited for {0}".format(retval))
+ >>> _ = eventlet.spawn(wait_on)
+ >>> evt.send('result')
+ >>> eventlet.sleep(0)
+ waited for result
+
+ Returns immediately if the event has already occurred.
+
+ >>> evt.wait()
+ 'result'
+
+ When the timeout argument is present and not None, it should be a floating point number
+ specifying a timeout for the operation in seconds (or fractions thereof).
+ """
+ current = greenlet.getcurrent()
+ if self._result is NOT_USED:
+ hub = hubs.get_hub()
+ self._waiters.add(current)
+ timer = None
+ if timeout is not None:
+ timer = hub.schedule_call_local(timeout, self._do_send, None, None, current)
+ try:
+ result = hub.switch()
+ if timer is not None:
+ timer.cancel()
+ return result
+ finally:
+ self._waiters.discard(current)
+ if self._exc is not None:
+ current.throw(*self._exc)
+ return self._result
+
+ def send(self, result=None, exc=None):
+ """Makes arrangements for the waiters to be woken with the
+ result and then returns immediately to the parent.
+
+ >>> from eventlet import event
+ >>> import eventlet
+ >>> evt = event.Event()
+ >>> def waiter():
+ ... print('about to wait')
+ ... result = evt.wait()
+ ... print('waited for {0}'.format(result))
+ >>> _ = eventlet.spawn(waiter)
+ >>> eventlet.sleep(0)
+ about to wait
+ >>> evt.send('a')
+ >>> eventlet.sleep(0)
+ waited for a
+
+ It is an error to call :meth:`send` multiple times on the same event.
+
+ >>> evt.send('whoops')
+ Traceback (most recent call last):
+ ...
+ AssertionError: Trying to re-send() an already-triggered event.
+
+ Use :meth:`reset` between :meth:`send` s to reuse an event object.
+ """
+ assert self._result is NOT_USED, 'Trying to re-send() an already-triggered event.'
+ self._result = result
+ if exc is not None and not isinstance(exc, tuple):
+ exc = (exc, )
+ self._exc = exc
+ hub = hubs.get_hub()
+ for waiter in self._waiters:
+ hub.schedule_call_global(
+ 0, self._do_send, self._result, self._exc, waiter)
+
+ def _do_send(self, result, exc, waiter):
+ if waiter in self._waiters:
+ if exc is None:
+ waiter.switch(result)
+ else:
+ waiter.throw(*exc)
+
+ def send_exception(self, *args):
+ """Same as :meth:`send`, but sends an exception to waiters.
+
+ The arguments to send_exception are the same as the arguments
+ to ``raise``. If a single exception object is passed in, it
+ will be re-raised when :meth:`wait` is called, generating a
+ new stacktrace.
+
+ >>> from eventlet import event
+ >>> evt = event.Event()
+ >>> evt.send_exception(RuntimeError())
+ >>> evt.wait()
+ Traceback (most recent call last):
+ File "", line 1, in
+ File "eventlet/event.py", line 120, in wait
+ current.throw(*self._exc)
+ RuntimeError
+
+ If it's important to preserve the entire original stack trace,
+ you must pass in the entire :func:`sys.exc_info` tuple.
+
+ >>> import sys
+ >>> evt = event.Event()
+ >>> try:
+ ... raise RuntimeError()
+ ... except RuntimeError:
+ ... evt.send_exception(*sys.exc_info())
+ ...
+ >>> evt.wait()
+ Traceback (most recent call last):
+ File "", line 1, in
+ File "eventlet/event.py", line 120, in wait
+ current.throw(*self._exc)
+ File "", line 2, in
+ RuntimeError
+
+ Note that doing so stores a traceback object directly on the
+ Event object, which may cause reference cycles. See the
+ :func:`sys.exc_info` documentation.
+ """
+ # the arguments and the same as for greenlet.throw
+ return self.send(None, args)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/greenpool.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/greenpool.py
new file mode 100644
index 0000000000000000000000000000000000000000..952659c3c3d6793de07fd2a22b43aed227450d1c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/greenpool.py
@@ -0,0 +1,257 @@
+import traceback
+
+import eventlet
+from eventlet import queue
+from eventlet.support import greenlets as greenlet
+import six
+
+__all__ = ['GreenPool', 'GreenPile']
+
+DEBUG = True
+
+
+class GreenPool(object):
+ """The GreenPool class is a pool of green threads.
+ """
+
+ def __init__(self, size=1000):
+ try:
+ size = int(size)
+ except ValueError as e:
+ msg = 'GreenPool() expect size :: int, actual: {0} {1}'.format(type(size), str(e))
+ raise TypeError(msg)
+ if size < 0:
+ msg = 'GreenPool() expect size >= 0, actual: {0}'.format(repr(size))
+ raise ValueError(msg)
+ self.size = size
+ self.coroutines_running = set()
+ self.sem = eventlet.Semaphore(size)
+ self.no_coros_running = eventlet.Event()
+
+ def resize(self, new_size):
+ """ Change the max number of greenthreads doing work at any given time.
+
+ If resize is called when there are more than *new_size* greenthreads
+ already working on tasks, they will be allowed to complete but no new
+ tasks will be allowed to get launched until enough greenthreads finish
+ their tasks to drop the overall quantity below *new_size*. Until
+ then, the return value of free() will be negative.
+ """
+ size_delta = new_size - self.size
+ self.sem.counter += size_delta
+ self.size = new_size
+
+ def running(self):
+ """ Returns the number of greenthreads that are currently executing
+ functions in the GreenPool."""
+ return len(self.coroutines_running)
+
+ def free(self):
+ """ Returns the number of greenthreads available for use.
+
+ If zero or less, the next call to :meth:`spawn` or :meth:`spawn_n` will
+ block the calling greenthread until a slot becomes available."""
+ return self.sem.counter
+
+ def spawn(self, function, *args, **kwargs):
+ """Run the *function* with its arguments in its own green thread.
+ Returns the :class:`GreenThread `
+ object that is running the function, which can be used to retrieve the
+ results.
+
+ If the pool is currently at capacity, ``spawn`` will block until one of
+ the running greenthreads completes its task and frees up a slot.
+
+ This function is reentrant; *function* can call ``spawn`` on the same
+ pool without risk of deadlocking the whole thing.
+ """
+ # if reentering an empty pool, don't try to wait on a coroutine freeing
+ # itself -- instead, just execute in the current coroutine
+ current = eventlet.getcurrent()
+ if self.sem.locked() and current in self.coroutines_running:
+ # a bit hacky to use the GT without switching to it
+ gt = eventlet.greenthread.GreenThread(current)
+ gt.main(function, args, kwargs)
+ return gt
+ else:
+ self.sem.acquire()
+ gt = eventlet.spawn(function, *args, **kwargs)
+ if not self.coroutines_running:
+ self.no_coros_running = eventlet.Event()
+ self.coroutines_running.add(gt)
+ gt.link(self._spawn_done)
+ return gt
+
+ def _spawn_n_impl(self, func, args, kwargs, coro):
+ try:
+ try:
+ func(*args, **kwargs)
+ except (KeyboardInterrupt, SystemExit, greenlet.GreenletExit):
+ raise
+ except:
+ if DEBUG:
+ traceback.print_exc()
+ finally:
+ if coro is None:
+ return
+ else:
+ coro = eventlet.getcurrent()
+ self._spawn_done(coro)
+
+ def spawn_n(self, function, *args, **kwargs):
+ """Create a greenthread to run the *function*, the same as
+ :meth:`spawn`. The difference is that :meth:`spawn_n` returns
+ None; the results of *function* are not retrievable.
+ """
+ # if reentering an empty pool, don't try to wait on a coroutine freeing
+ # itself -- instead, just execute in the current coroutine
+ current = eventlet.getcurrent()
+ if self.sem.locked() and current in self.coroutines_running:
+ self._spawn_n_impl(function, args, kwargs, None)
+ else:
+ self.sem.acquire()
+ g = eventlet.spawn_n(
+ self._spawn_n_impl,
+ function, args, kwargs, True)
+ if not self.coroutines_running:
+ self.no_coros_running = eventlet.Event()
+ self.coroutines_running.add(g)
+
+ def waitall(self):
+ """Waits until all greenthreads in the pool are finished working."""
+ assert eventlet.getcurrent() not in self.coroutines_running, \
+ "Calling waitall() from within one of the " \
+ "GreenPool's greenthreads will never terminate."
+ if self.running():
+ self.no_coros_running.wait()
+
+ def _spawn_done(self, coro):
+ self.sem.release()
+ if coro is not None:
+ self.coroutines_running.remove(coro)
+ # if done processing (no more work is waiting for processing),
+ # we can finish off any waitall() calls that might be pending
+ if self.sem.balance == self.size:
+ self.no_coros_running.send(None)
+
+ def waiting(self):
+ """Return the number of greenthreads waiting to spawn.
+ """
+ if self.sem.balance < 0:
+ return -self.sem.balance
+ else:
+ return 0
+
+ def _do_map(self, func, it, gi):
+ for args in it:
+ gi.spawn(func, *args)
+ gi.done_spawning()
+
+ def starmap(self, function, iterable):
+ """This is the same as :func:`itertools.starmap`, except that *func* is
+ executed in a separate green thread for each item, with the concurrency
+ limited by the pool's size. In operation, starmap consumes a constant
+ amount of memory, proportional to the size of the pool, and is thus
+ suited for iterating over extremely long input lists.
+ """
+ if function is None:
+ function = lambda *a: a
+ # We use a whole separate greenthread so its spawn() calls can block
+ # without blocking OUR caller. On the other hand, we must assume that
+ # our caller will immediately start trying to iterate over whatever we
+ # return. If that were a GreenPile, our caller would always see an
+ # empty sequence because the hub hasn't even entered _do_map() yet --
+ # _do_map() hasn't had a chance to spawn a single greenthread on this
+ # GreenPool! A GreenMap is safe to use with different producer and
+ # consumer greenthreads, because it doesn't raise StopIteration until
+ # the producer has explicitly called done_spawning().
+ gi = GreenMap(self.size)
+ eventlet.spawn_n(self._do_map, function, iterable, gi)
+ return gi
+
+ def imap(self, function, *iterables):
+ """This is the same as :func:`itertools.imap`, and has the same
+ concurrency and memory behavior as :meth:`starmap`.
+
+ It's quite convenient for, e.g., farming out jobs from a file::
+
+ def worker(line):
+ return do_something(line)
+ pool = GreenPool()
+ for result in pool.imap(worker, open("filename", 'r')):
+ print(result)
+ """
+ return self.starmap(function, six.moves.zip(*iterables))
+
+
+class GreenPile(object):
+ """GreenPile is an abstraction representing a bunch of I/O-related tasks.
+
+ Construct a GreenPile with an existing GreenPool object. The GreenPile will
+ then use that pool's concurrency as it processes its jobs. There can be
+ many GreenPiles associated with a single GreenPool.
+
+ A GreenPile can also be constructed standalone, not associated with any
+ GreenPool. To do this, construct it with an integer size parameter instead
+ of a GreenPool.
+
+ It is not advisable to iterate over a GreenPile in a different greenthread
+ than the one which is calling spawn. The iterator will exit early in that
+ situation.
+ """
+
+ def __init__(self, size_or_pool=1000):
+ if isinstance(size_or_pool, GreenPool):
+ self.pool = size_or_pool
+ else:
+ self.pool = GreenPool(size_or_pool)
+ self.waiters = queue.LightQueue()
+ self.counter = 0
+
+ def spawn(self, func, *args, **kw):
+ """Runs *func* in its own green thread, with the result available by
+ iterating over the GreenPile object."""
+ self.counter += 1
+ try:
+ gt = self.pool.spawn(func, *args, **kw)
+ self.waiters.put(gt)
+ except:
+ self.counter -= 1
+ raise
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ """Wait for the next result, suspending the current greenthread until it
+ is available. Raises StopIteration when there are no more results."""
+ if self.counter == 0:
+ raise StopIteration()
+ return self._next()
+ __next__ = next
+
+ def _next(self):
+ try:
+ return self.waiters.get().wait()
+ finally:
+ self.counter -= 1
+
+
+# this is identical to GreenPile but it blocks on spawn if the results
+# aren't consumed, and it doesn't generate its own StopIteration exception,
+# instead relying on the spawning process to send one in when it's done
+class GreenMap(GreenPile):
+ def __init__(self, size_or_pool):
+ super(GreenMap, self).__init__(size_or_pool)
+ self.waiters = queue.LightQueue(maxsize=self.pool.size)
+
+ def done_spawning(self):
+ self.spawn(lambda: StopIteration())
+
+ def next(self):
+ val = self._next()
+ if isinstance(val, StopIteration):
+ raise val
+ else:
+ return val
+ __next__ = next
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/greenthread.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/greenthread.py
new file mode 100644
index 0000000000000000000000000000000000000000..28f0a57c5b18545cfa778337c6010f2752dc85cf
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/greenthread.py
@@ -0,0 +1,303 @@
+from collections import deque
+import sys
+
+from eventlet import event
+from eventlet import hubs
+from eventlet import support
+from eventlet import timeout
+from eventlet.hubs import timer
+from eventlet.support import greenlets as greenlet
+import six
+import warnings
+
+__all__ = ['getcurrent', 'sleep', 'spawn', 'spawn_n',
+ 'kill',
+ 'spawn_after', 'spawn_after_local', 'GreenThread']
+
+getcurrent = greenlet.getcurrent
+
+
+def sleep(seconds=0):
+ """Yield control to another eligible coroutine until at least *seconds* have
+ elapsed.
+
+ *seconds* may be specified as an integer, or a float if fractional seconds
+ are desired. Calling :func:`~greenthread.sleep` with *seconds* of 0 is the
+ canonical way of expressing a cooperative yield. For example, if one is
+ looping over a large list performing an expensive calculation without
+ calling any socket methods, it's a good idea to call ``sleep(0)``
+ occasionally; otherwise nothing else will run.
+ """
+ hub = hubs.get_hub()
+ current = getcurrent()
+ assert hub.greenlet is not current, 'do not call blocking functions from the mainloop'
+ timer = hub.schedule_call_global(seconds, current.switch)
+ try:
+ hub.switch()
+ finally:
+ timer.cancel()
+
+
+def spawn(func, *args, **kwargs):
+ """Create a greenthread to run ``func(*args, **kwargs)``. Returns a
+ :class:`GreenThread` object which you can use to get the results of the
+ call.
+
+ Execution control returns immediately to the caller; the created greenthread
+ is merely scheduled to be run at the next available opportunity.
+ Use :func:`spawn_after` to arrange for greenthreads to be spawned
+ after a finite delay.
+ """
+ hub = hubs.get_hub()
+ g = GreenThread(hub.greenlet)
+ hub.schedule_call_global(0, g.switch, func, args, kwargs)
+ return g
+
+
+def spawn_n(func, *args, **kwargs):
+ """Same as :func:`spawn`, but returns a ``greenlet`` object from
+ which it is not possible to retrieve either a return value or
+ whether it raised any exceptions. This is faster than
+ :func:`spawn`; it is fastest if there are no keyword arguments.
+
+ If an exception is raised in the function, spawn_n prints a stack
+ trace; the print can be disabled by calling
+ :func:`eventlet.debug.hub_exceptions` with False.
+ """
+ return _spawn_n(0, func, args, kwargs)[1]
+
+
+def spawn_after(seconds, func, *args, **kwargs):
+ """Spawns *func* after *seconds* have elapsed. It runs as scheduled even if
+ the current greenthread has completed.
+
+ *seconds* may be specified as an integer, or a float if fractional seconds
+ are desired. The *func* will be called with the given *args* and
+ keyword arguments *kwargs*, and will be executed within its own greenthread.
+
+ The return value of :func:`spawn_after` is a :class:`GreenThread` object,
+ which can be used to retrieve the results of the call.
+
+ To cancel the spawn and prevent *func* from being called,
+ call :meth:`GreenThread.cancel` on the return value of :func:`spawn_after`.
+ This will not abort the function if it's already started running, which is
+ generally the desired behavior. If terminating *func* regardless of whether
+ it's started or not is the desired behavior, call :meth:`GreenThread.kill`.
+ """
+ hub = hubs.get_hub()
+ g = GreenThread(hub.greenlet)
+ hub.schedule_call_global(seconds, g.switch, func, args, kwargs)
+ return g
+
+
+def spawn_after_local(seconds, func, *args, **kwargs):
+ """Spawns *func* after *seconds* have elapsed. The function will NOT be
+ called if the current greenthread has exited.
+
+ *seconds* may be specified as an integer, or a float if fractional seconds
+ are desired. The *func* will be called with the given *args* and
+ keyword arguments *kwargs*, and will be executed within its own greenthread.
+
+ The return value of :func:`spawn_after` is a :class:`GreenThread` object,
+ which can be used to retrieve the results of the call.
+
+ To cancel the spawn and prevent *func* from being called,
+ call :meth:`GreenThread.cancel` on the return value. This will not abort the
+ function if it's already started running. If terminating *func* regardless
+ of whether it's started or not is the desired behavior, call
+ :meth:`GreenThread.kill`.
+ """
+ hub = hubs.get_hub()
+ g = GreenThread(hub.greenlet)
+ hub.schedule_call_local(seconds, g.switch, func, args, kwargs)
+ return g
+
+
+def call_after_global(seconds, func, *args, **kwargs):
+ warnings.warn(
+ "call_after_global is renamed to spawn_after, which"
+ "has the same signature and semantics (plus a bit extra). Please do a"
+ " quick search-and-replace on your codebase, thanks!",
+ DeprecationWarning, stacklevel=2)
+ return _spawn_n(seconds, func, args, kwargs)[0]
+
+
+def call_after_local(seconds, function, *args, **kwargs):
+ warnings.warn(
+ "call_after_local is renamed to spawn_after_local, which"
+ "has the same signature and semantics (plus a bit extra).",
+ DeprecationWarning, stacklevel=2)
+ hub = hubs.get_hub()
+ g = greenlet.greenlet(function, parent=hub.greenlet)
+ t = hub.schedule_call_local(seconds, g.switch, *args, **kwargs)
+ return t
+
+
+call_after = call_after_local
+
+
+def exc_after(seconds, *throw_args):
+ warnings.warn("Instead of exc_after, which is deprecated, use "
+ "Timeout(seconds, exception)",
+ DeprecationWarning, stacklevel=2)
+ if seconds is None: # dummy argument, do nothing
+ return timer.Timer(seconds, lambda: None)
+ hub = hubs.get_hub()
+ return hub.schedule_call_local(seconds, getcurrent().throw, *throw_args)
+
+
+# deprecate, remove
+TimeoutError, with_timeout = (
+ support.wrap_deprecated(old, new)(fun) for old, new, fun in (
+ ('greenthread.TimeoutError', 'Timeout', timeout.Timeout),
+ ('greenthread.with_timeout', 'with_timeout', timeout.with_timeout),
+ ))
+
+
+def _spawn_n(seconds, func, args, kwargs):
+ hub = hubs.get_hub()
+ g = greenlet.greenlet(func, parent=hub.greenlet)
+ t = hub.schedule_call_global(seconds, g.switch, *args, **kwargs)
+ return t, g
+
+
+class GreenThread(greenlet.greenlet):
+ """The GreenThread class is a type of Greenlet which has the additional
+ property of being able to retrieve the return value of the main function.
+ Do not construct GreenThread objects directly; call :func:`spawn` to get one.
+ """
+
+ def __init__(self, parent):
+ greenlet.greenlet.__init__(self, self.main, parent)
+ self._exit_event = event.Event()
+ self._resolving_links = False
+ self._exit_funcs = None
+
+ def wait(self):
+ """ Returns the result of the main function of this GreenThread. If the
+ result is a normal return value, :meth:`wait` returns it. If it raised
+ an exception, :meth:`wait` will raise the same exception (though the
+ stack trace will unavoidably contain some frames from within the
+ greenthread module)."""
+ return self._exit_event.wait()
+
+ def link(self, func, *curried_args, **curried_kwargs):
+ """ Set up a function to be called with the results of the GreenThread.
+
+ The function must have the following signature::
+
+ def func(gt, [curried args/kwargs]):
+
+ When the GreenThread finishes its run, it calls *func* with itself
+ and with the `curried arguments `_ supplied
+ at link-time. If the function wants to retrieve the result of the GreenThread,
+ it should call wait() on its first argument.
+
+ Note that *func* is called within execution context of
+ the GreenThread, so it is possible to interfere with other linked
+ functions by doing things like switching explicitly to another
+ greenthread.
+ """
+ if self._exit_funcs is None:
+ self._exit_funcs = deque()
+ self._exit_funcs.append((func, curried_args, curried_kwargs))
+ if self._exit_event.ready():
+ self._resolve_links()
+
+ def unlink(self, func, *curried_args, **curried_kwargs):
+ """ remove linked function set by :meth:`link`
+
+ Remove successfully return True, otherwise False
+ """
+ if not self._exit_funcs:
+ return False
+ try:
+ self._exit_funcs.remove((func, curried_args, curried_kwargs))
+ return True
+ except ValueError:
+ return False
+
+ def main(self, function, args, kwargs):
+ try:
+ result = function(*args, **kwargs)
+ except:
+ self._exit_event.send_exception(*sys.exc_info())
+ self._resolve_links()
+ raise
+ else:
+ self._exit_event.send(result)
+ self._resolve_links()
+
+ def _resolve_links(self):
+ # ca and ckw are the curried function arguments
+ if self._resolving_links:
+ return
+ if not self._exit_funcs:
+ return
+ self._resolving_links = True
+ try:
+ while self._exit_funcs:
+ f, ca, ckw = self._exit_funcs.popleft()
+ f(self, *ca, **ckw)
+ finally:
+ self._resolving_links = False
+
+ def kill(self, *throw_args):
+ """Kills the greenthread using :func:`kill`. After being killed
+ all calls to :meth:`wait` will raise *throw_args* (which default
+ to :class:`greenlet.GreenletExit`)."""
+ return kill(self, *throw_args)
+
+ def cancel(self, *throw_args):
+ """Kills the greenthread using :func:`kill`, but only if it hasn't
+ already started running. After being canceled,
+ all calls to :meth:`wait` will raise *throw_args* (which default
+ to :class:`greenlet.GreenletExit`)."""
+ return cancel(self, *throw_args)
+
+
+def cancel(g, *throw_args):
+ """Like :func:`kill`, but only terminates the greenthread if it hasn't
+ already started execution. If the grenthread has already started
+ execution, :func:`cancel` has no effect."""
+ if not g:
+ kill(g, *throw_args)
+
+
+def kill(g, *throw_args):
+ """Terminates the target greenthread by raising an exception into it.
+ Whatever that greenthread might be doing; be it waiting for I/O or another
+ primitive, it sees an exception right away.
+
+ By default, this exception is GreenletExit, but a specific exception
+ may be specified. *throw_args* should be the same as the arguments to
+ raise; either an exception instance or an exc_info tuple.
+
+ Calling :func:`kill` causes the calling greenthread to cooperatively yield.
+ """
+ if g.dead:
+ return
+ hub = hubs.get_hub()
+ if not g:
+ # greenlet hasn't started yet and therefore throw won't work
+ # on its own; semantically we want it to be as though the main
+ # method never got called
+ def just_raise(*a, **kw):
+ if throw_args:
+ six.reraise(throw_args[0], throw_args[1], throw_args[2])
+ else:
+ raise greenlet.GreenletExit()
+ g.run = just_raise
+ if isinstance(g, GreenThread):
+ # it's a GreenThread object, so we want to call its main
+ # method to take advantage of the notification
+ try:
+ g.main(just_raise, (), {})
+ except:
+ pass
+ current = getcurrent()
+ if current is not hub.greenlet:
+ # arrange to wake the caller back up immediately
+ hub.ensure_greenlet()
+ hub.schedule_call_global(0, current.switch)
+ g.throw(*throw_args)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/lock.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/lock.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b21e0b4558b7fe76e85d7c344a6d8883fd7524e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/lock.py
@@ -0,0 +1,37 @@
+from eventlet import hubs
+from eventlet.semaphore import Semaphore
+
+
+class Lock(Semaphore):
+
+ """A lock.
+ This is API-compatible with :class:`threading.Lock`.
+
+ It is a context manager, and thus can be used in a with block::
+
+ lock = Lock()
+ with lock:
+ do_some_stuff()
+ """
+
+ def release(self, blocking=True):
+ """Modify behaviour vs :class:`Semaphore` to raise a RuntimeError
+ exception if the value is greater than zero. This corrects behaviour
+ to realign with :class:`threading.Lock`.
+ """
+ if self.counter > 0:
+ raise RuntimeError("release unlocked lock")
+
+ # Consciously *do not* call super().release(), but instead inline
+ # Semaphore.release() here. We've seen issues with logging._lock
+ # deadlocking because garbage collection happened to run mid-release
+ # and eliminating the extra stack frame should help prevent that.
+ # See https://github.com/eventlet/eventlet/issues/742
+ self.counter += 1
+ if self._waiters:
+ hubs.get_hub().schedule_call_global(0, self._do_acquire)
+ return True
+
+ def _at_fork_reinit(self):
+ self.counter = 1
+ self._waiters.clear()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/patcher.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/patcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..32506ea7f079b4276de6bf054617ca6c2b81c080
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/patcher.py
@@ -0,0 +1,572 @@
+try:
+ import _imp as imp
+except ImportError:
+ import imp
+import sys
+try:
+ # Only for this purpose, it's irrelevant if `os` was already patched.
+ # https://github.com/eventlet/eventlet/pull/661
+ from os import register_at_fork
+except ImportError:
+ register_at_fork = None
+
+import eventlet
+import six
+
+
+__all__ = ['inject', 'import_patched', 'monkey_patch', 'is_monkey_patched']
+
+__exclude = set(('__builtins__', '__file__', '__name__'))
+
+
+class SysModulesSaver(object):
+ """Class that captures some subset of the current state of
+ sys.modules. Pass in an iterator of module names to the
+ constructor."""
+
+ def __init__(self, module_names=()):
+ self._saved = {}
+ imp.acquire_lock()
+ self.save(*module_names)
+
+ def save(self, *module_names):
+ """Saves the named modules to the object."""
+ for modname in module_names:
+ self._saved[modname] = sys.modules.get(modname, None)
+
+ def restore(self):
+ """Restores the modules that the saver knows about into
+ sys.modules.
+ """
+ try:
+ for modname, mod in six.iteritems(self._saved):
+ if mod is not None:
+ sys.modules[modname] = mod
+ else:
+ try:
+ del sys.modules[modname]
+ except KeyError:
+ pass
+ finally:
+ imp.release_lock()
+
+
+def inject(module_name, new_globals, *additional_modules):
+ """Base method for "injecting" greened modules into an imported module. It
+ imports the module specified in *module_name*, arranging things so
+ that the already-imported modules in *additional_modules* are used when
+ *module_name* makes its imports.
+
+ **Note:** This function does not create or change any sys.modules item, so
+ if your greened module use code like 'sys.modules["your_module_name"]', you
+ need to update sys.modules by yourself.
+
+ *new_globals* is either None or a globals dictionary that gets populated
+ with the contents of the *module_name* module. This is useful when creating
+ a "green" version of some other module.
+
+ *additional_modules* should be a collection of two-element tuples, of the
+ form (, ). If it's not specified, a default selection of
+ name/module pairs is used, which should cover all use cases but may be
+ slower because there are inevitably redundant or unnecessary imports.
+ """
+ patched_name = '__patched_module_' + module_name
+ if patched_name in sys.modules:
+ # returning already-patched module so as not to destroy existing
+ # references to patched modules
+ return sys.modules[patched_name]
+
+ if not additional_modules:
+ # supply some defaults
+ additional_modules = (
+ _green_os_modules() +
+ _green_select_modules() +
+ _green_socket_modules() +
+ _green_thread_modules() +
+ _green_time_modules())
+ # _green_MySQLdb()) # enable this after a short baking-in period
+
+ # after this we are gonna screw with sys.modules, so capture the
+ # state of all the modules we're going to mess with, and lock
+ saver = SysModulesSaver([name for name, m in additional_modules])
+ saver.save(module_name)
+
+ # Cover the target modules so that when you import the module it
+ # sees only the patched versions
+ for name, mod in additional_modules:
+ sys.modules[name] = mod
+
+ # Remove the old module from sys.modules and reimport it while
+ # the specified modules are in place
+ sys.modules.pop(module_name, None)
+ # Also remove sub modules and reimport. Use copy the keys to list
+ # because of the pop operations will change the content of sys.modules
+ # within th loop
+ for imported_module_name in list(sys.modules.keys()):
+ if imported_module_name.startswith(module_name + '.'):
+ sys.modules.pop(imported_module_name, None)
+ try:
+ module = __import__(module_name, {}, {}, module_name.split('.')[:-1])
+
+ if new_globals is not None:
+ # Update the given globals dictionary with everything from this new module
+ for name in dir(module):
+ if name not in __exclude:
+ new_globals[name] = getattr(module, name)
+
+ # Keep a reference to the new module to prevent it from dying
+ sys.modules[patched_name] = module
+ finally:
+ saver.restore() # Put the original modules back
+
+ return module
+
+
+def import_patched(module_name, *additional_modules, **kw_additional_modules):
+ """Imports a module in a way that ensures that the module uses "green"
+ versions of the standard library modules, so that everything works
+ nonblockingly.
+
+ The only required argument is the name of the module to be imported.
+ """
+ return inject(
+ module_name,
+ None,
+ *additional_modules + tuple(kw_additional_modules.items()))
+
+
+def patch_function(func, *additional_modules):
+ """Decorator that returns a version of the function that patches
+ some modules for the duration of the function call. This is
+ deeply gross and should only be used for functions that import
+ network libraries within their function bodies that there is no
+ way of getting around."""
+ if not additional_modules:
+ # supply some defaults
+ additional_modules = (
+ _green_os_modules() +
+ _green_select_modules() +
+ _green_socket_modules() +
+ _green_thread_modules() +
+ _green_time_modules())
+
+ def patched(*args, **kw):
+ saver = SysModulesSaver()
+ for name, mod in additional_modules:
+ saver.save(name)
+ sys.modules[name] = mod
+ try:
+ return func(*args, **kw)
+ finally:
+ saver.restore()
+ return patched
+
+
+def _original_patch_function(func, *module_names):
+ """Kind of the contrapositive of patch_function: decorates a
+ function such that when it's called, sys.modules is populated only
+ with the unpatched versions of the specified modules. Unlike
+ patch_function, only the names of the modules need be supplied,
+ and there are no defaults. This is a gross hack; tell your kids not
+ to import inside function bodies!"""
+ def patched(*args, **kw):
+ saver = SysModulesSaver(module_names)
+ for name in module_names:
+ sys.modules[name] = original(name)
+ try:
+ return func(*args, **kw)
+ finally:
+ saver.restore()
+ return patched
+
+
+def original(modname):
+ """ This returns an unpatched version of a module; this is useful for
+ Eventlet itself (i.e. tpool)."""
+ # note that it's not necessary to temporarily install unpatched
+ # versions of all patchable modules during the import of the
+ # module; this is because none of them import each other, except
+ # for threading which imports thread
+ original_name = '__original_module_' + modname
+ if original_name in sys.modules:
+ return sys.modules.get(original_name)
+
+ # re-import the "pure" module and store it in the global _originals
+ # dict; be sure to restore whatever module had that name already
+ saver = SysModulesSaver((modname,))
+ sys.modules.pop(modname, None)
+ # some rudimentary dependency checking -- fortunately the modules
+ # we're working on don't have many dependencies so we can just do
+ # some special-casing here
+ if six.PY2:
+ deps = {'threading': 'thread', 'Queue': 'threading'}
+ if six.PY3:
+ deps = {'threading': '_thread', 'queue': 'threading'}
+ if modname in deps:
+ dependency = deps[modname]
+ saver.save(dependency)
+ sys.modules[dependency] = original(dependency)
+ try:
+ real_mod = __import__(modname, {}, {}, modname.split('.')[:-1])
+ if modname in ('Queue', 'queue') and not hasattr(real_mod, '_threading'):
+ # tricky hack: Queue's constructor in <2.7 imports
+ # threading on every instantiation; therefore we wrap
+ # it so that it always gets the original threading
+ real_mod.Queue.__init__ = _original_patch_function(
+ real_mod.Queue.__init__,
+ 'threading')
+ # save a reference to the unpatched module so it doesn't get lost
+ sys.modules[original_name] = real_mod
+ finally:
+ saver.restore()
+
+ return sys.modules[original_name]
+
+
+already_patched = {}
+
+
+def monkey_patch(**on):
+ """Globally patches certain system modules to be greenthread-friendly.
+
+ The keyword arguments afford some control over which modules are patched.
+ If no keyword arguments are supplied, all possible modules are patched.
+ If keywords are set to True, only the specified modules are patched. E.g.,
+ ``monkey_patch(socket=True, select=True)`` patches only the select and
+ socket modules. Most arguments patch the single module of the same name
+ (os, time, select). The exceptions are socket, which also patches the ssl
+ module if present; and thread, which patches thread, threading, and Queue.
+
+ It's safe to call monkey_patch multiple times.
+ """
+
+ # Workaround for import cycle observed as following in monotonic
+ # RuntimeError: no suitable implementation for this system
+ # see https://github.com/eventlet/eventlet/issues/401#issuecomment-325015989
+ #
+ # Make sure the hub is completely imported before any
+ # monkey-patching, or we risk recursion if the process of importing
+ # the hub calls into monkey-patched modules.
+ eventlet.hubs.get_hub()
+
+ accepted_args = set(('os', 'select', 'socket',
+ 'thread', 'time', 'psycopg', 'MySQLdb',
+ 'builtins', 'subprocess'))
+ # To make sure only one of them is passed here
+ assert not ('__builtin__' in on and 'builtins' in on)
+ try:
+ b = on.pop('__builtin__')
+ except KeyError:
+ pass
+ else:
+ on['builtins'] = b
+
+ default_on = on.pop("all", None)
+
+ for k in six.iterkeys(on):
+ if k not in accepted_args:
+ raise TypeError("monkey_patch() got an unexpected "
+ "keyword argument %r" % k)
+ if default_on is None:
+ default_on = not (True in on.values())
+ for modname in accepted_args:
+ if modname == 'MySQLdb':
+ # MySQLdb is only on when explicitly patched for the moment
+ on.setdefault(modname, False)
+ if modname == 'builtins':
+ on.setdefault(modname, False)
+ on.setdefault(modname, default_on)
+
+ if on['thread'] and not already_patched.get('thread'):
+ _green_existing_locks()
+
+ modules_to_patch = []
+ for name, modules_function in [
+ ('os', _green_os_modules),
+ ('select', _green_select_modules),
+ ('socket', _green_socket_modules),
+ ('thread', _green_thread_modules),
+ ('time', _green_time_modules),
+ ('MySQLdb', _green_MySQLdb),
+ ('builtins', _green_builtins),
+ ('subprocess', _green_subprocess_modules),
+ ]:
+ if on[name] and not already_patched.get(name):
+ modules_to_patch += modules_function()
+ already_patched[name] = True
+
+ if on['psycopg'] and not already_patched.get('psycopg'):
+ try:
+ from eventlet.support import psycopg2_patcher
+ psycopg2_patcher.make_psycopg_green()
+ already_patched['psycopg'] = True
+ except ImportError:
+ # note that if we get an importerror from trying to
+ # monkeypatch psycopg, we will continually retry it
+ # whenever monkey_patch is called; this should not be a
+ # performance problem but it allows is_monkey_patched to
+ # tell us whether or not we succeeded
+ pass
+
+ _threading = original('threading')
+ imp.acquire_lock()
+ try:
+ for name, mod in modules_to_patch:
+ orig_mod = sys.modules.get(name)
+ if orig_mod is None:
+ orig_mod = __import__(name)
+ for attr_name in mod.__patched__:
+ patched_attr = getattr(mod, attr_name, None)
+ if patched_attr is not None:
+ setattr(orig_mod, attr_name, patched_attr)
+ deleted = getattr(mod, '__deleted__', [])
+ for attr_name in deleted:
+ if hasattr(orig_mod, attr_name):
+ delattr(orig_mod, attr_name)
+
+ # https://github.com/eventlet/eventlet/issues/592
+ if name == 'threading' and register_at_fork:
+ def fix_threading_active(
+ _global_dict=_threading.current_thread.__globals__,
+ # alias orig_mod as patched to reflect its new state
+ # https://github.com/eventlet/eventlet/pull/661#discussion_r509877481
+ _patched=orig_mod,
+ ):
+ _prefork_active = [None]
+
+ def before_fork():
+ _prefork_active[0] = _global_dict['_active']
+ _global_dict['_active'] = _patched._active
+
+ def after_fork():
+ _global_dict['_active'] = _prefork_active[0]
+
+ register_at_fork(
+ before=before_fork,
+ after_in_parent=after_fork)
+ fix_threading_active()
+ finally:
+ imp.release_lock()
+
+ if sys.version_info >= (3, 3):
+ import importlib._bootstrap
+ thread = original('_thread')
+ # importlib must use real thread locks, not eventlet.Semaphore
+ importlib._bootstrap._thread = thread
+
+ # Issue #185: Since Python 3.3, threading.RLock is implemented in C and
+ # so call a C function to get the thread identifier, instead of calling
+ # threading.get_ident(). Force the Python implementation of RLock which
+ # calls threading.get_ident() and so is compatible with eventlet.
+ import threading
+ threading.RLock = threading._PyRLock
+
+ # Issue #508: Since Python 3.7 queue.SimpleQueue is implemented in C,
+ # causing a deadlock. Replace the C implementation with the Python one.
+ if sys.version_info >= (3, 7):
+ import queue
+ queue.SimpleQueue = queue._PySimpleQueue
+
+
+def is_monkey_patched(module):
+ """Returns True if the given module is monkeypatched currently, False if
+ not. *module* can be either the module itself or its name.
+
+ Based entirely off the name of the module, so if you import a
+ module some other way than with the import keyword (including
+ import_patched), this might not be correct about that particular
+ module."""
+ return module in already_patched or \
+ getattr(module, '__name__', None) in already_patched
+
+
+def _green_existing_locks():
+ """Make locks created before monkey-patching safe.
+
+ RLocks rely on a Lock and on Python 2, if an unpatched Lock blocks, it
+ blocks the native thread. We need to replace these with green Locks.
+
+ This was originally noticed in the stdlib logging module."""
+ import gc
+ import threading
+ import eventlet.green.thread
+ lock_type = type(threading.Lock())
+ rlock_type = type(threading.RLock())
+ if hasattr(threading, '_PyRLock'):
+ # this happens on CPython3 and PyPy >= 7.0.0: "py3-style" rlocks, they
+ # are implemented natively in C and RPython respectively
+ py3_style = True
+ pyrlock_type = type(threading._PyRLock())
+ else:
+ # this happens on CPython2.7 and PyPy < 7.0.0: "py2-style" rlocks,
+ # they are implemented in pure-python
+ py3_style = False
+ pyrlock_type = None
+
+ # We're monkey-patching so there can't be any greenlets yet, ergo our thread
+ # ID is the only valid owner possible.
+ tid = eventlet.green.thread.get_ident()
+ for obj in gc.get_objects():
+ if isinstance(obj, rlock_type):
+ if not py3_style and isinstance(obj._RLock__block, lock_type):
+ _fix_py2_rlock(obj, tid)
+ elif py3_style and not isinstance(obj, pyrlock_type):
+ _fix_py3_rlock(obj, tid)
+
+ if sys.version_info < (3, 10):
+ # Older py3 won't have RLocks show up in gc.get_objects() -- see
+ # https://github.com/eventlet/eventlet/issues/546 -- so green a handful
+ # that we know are significant
+ import logging
+ if isinstance(logging._lock, rlock_type):
+ _fix_py3_rlock(logging._lock, tid)
+ logging._acquireLock()
+ try:
+ for ref in logging._handlerList:
+ handler = ref()
+ if handler and isinstance(handler.lock, rlock_type):
+ _fix_py3_rlock(handler.lock, tid)
+ del handler
+ finally:
+ logging._releaseLock()
+
+
+def _fix_py2_rlock(rlock, tid):
+ import eventlet.green.threading
+ old = rlock._RLock__block
+ new = eventlet.green.threading.Lock()
+ rlock._RLock__block = new
+ if old.locked():
+ new.acquire()
+ rlock._RLock__owner = tid
+
+
+def _fix_py3_rlock(old, tid):
+ import gc
+ import threading
+ from eventlet.green.thread import allocate_lock
+ new = threading._PyRLock()
+ if not hasattr(new, "_block") or not hasattr(new, "_owner"):
+ # These will only fail if Python changes its internal implementation of
+ # _PyRLock:
+ raise RuntimeError(
+ "INTERNAL BUG. Perhaps you are using a major version " +
+ "of Python that is unsupported by eventlet? Please file a bug " +
+ "at https://github.com/eventlet/eventlet/issues/new")
+ new._block = allocate_lock()
+ acquired = False
+ while old._is_owned():
+ old.release()
+ new.acquire()
+ acquired = True
+ if old._is_owned():
+ new.acquire()
+ acquired = True
+ if acquired:
+ new._owner = tid
+ gc.collect()
+ for ref in gc.get_referrers(old):
+ if isinstance(ref, dict):
+ for k, v in list(ref.items()):
+ if v is old:
+ ref[k] = new
+ continue
+ if isinstance(ref, list):
+ for i, v in enumerate(ref):
+ if v is old:
+ ref[i] = new
+ continue
+ try:
+ ref_vars = vars(ref)
+ except TypeError:
+ pass
+ else:
+ for k, v in ref_vars.items():
+ if v is old:
+ setattr(ref, k, new)
+
+
+def _green_os_modules():
+ from eventlet.green import os
+ return [('os', os)]
+
+
+def _green_select_modules():
+ from eventlet.green import select
+ modules = [('select', select)]
+
+ if sys.version_info >= (3, 4):
+ from eventlet.green import selectors
+ modules.append(('selectors', selectors))
+
+ return modules
+
+
+def _green_socket_modules():
+ from eventlet.green import socket
+ try:
+ from eventlet.green import ssl
+ return [('socket', socket), ('ssl', ssl)]
+ except ImportError:
+ return [('socket', socket)]
+
+
+def _green_subprocess_modules():
+ from eventlet.green import subprocess
+ return [('subprocess', subprocess)]
+
+
+def _green_thread_modules():
+ from eventlet.green import Queue
+ from eventlet.green import thread
+ from eventlet.green import threading
+ if six.PY2:
+ return [('Queue', Queue), ('thread', thread), ('threading', threading)]
+ if six.PY3:
+ return [('queue', Queue), ('_thread', thread), ('threading', threading)]
+
+
+def _green_time_modules():
+ from eventlet.green import time
+ return [('time', time)]
+
+
+def _green_MySQLdb():
+ try:
+ from eventlet.green import MySQLdb
+ return [('MySQLdb', MySQLdb)]
+ except ImportError:
+ return []
+
+
+def _green_builtins():
+ try:
+ from eventlet.green import builtin
+ return [('__builtin__' if six.PY2 else 'builtins', builtin)]
+ except ImportError:
+ return []
+
+
+def slurp_properties(source, destination, ignore=[], srckeys=None):
+ """Copy properties from *source* (assumed to be a module) to
+ *destination* (assumed to be a dict).
+
+ *ignore* lists properties that should not be thusly copied.
+ *srckeys* is a list of keys to copy, if the source's __all__ is
+ untrustworthy.
+ """
+ if srckeys is None:
+ srckeys = source.__all__
+ destination.update(dict([
+ (name, getattr(source, name))
+ for name in srckeys
+ if not (name.startswith('__') or name in ignore)
+ ]))
+
+
+if __name__ == "__main__":
+ sys.argv.pop(0)
+ monkey_patch()
+ with open(sys.argv[0]) as f:
+ code = compile(f.read(), sys.argv[0], 'exec')
+ exec(code)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/pools.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/pools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee9b77bbeb6483d0211bdb8d7b8f081953c64904
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/pools.py
@@ -0,0 +1,186 @@
+from __future__ import print_function
+
+import collections
+from contextlib import contextmanager
+
+from eventlet import queue
+
+
+__all__ = ['Pool', 'TokenPool']
+
+
+class Pool(object):
+ """
+ Pool class implements resource limitation and construction.
+
+ There are two ways of using Pool: passing a `create` argument or
+ subclassing. In either case you must provide a way to create
+ the resource.
+
+ When using `create` argument, pass a function with no arguments::
+
+ http_pool = pools.Pool(create=httplib2.Http)
+
+ If you need to pass arguments, build a nullary function with either
+ `lambda` expression::
+
+ http_pool = pools.Pool(create=lambda: httplib2.Http(timeout=90))
+
+ or :func:`functools.partial`::
+
+ from functools import partial
+ http_pool = pools.Pool(create=partial(httplib2.Http, timeout=90))
+
+ When subclassing, define only the :meth:`create` method
+ to implement the desired resource::
+
+ class MyPool(pools.Pool):
+ def create(self):
+ return MyObject()
+
+ If using 2.5 or greater, the :meth:`item` method acts as a context manager;
+ that's the best way to use it::
+
+ with mypool.item() as thing:
+ thing.dostuff()
+
+ The maximum size of the pool can be modified at runtime via
+ the :meth:`resize` method.
+
+ Specifying a non-zero *min-size* argument pre-populates the pool with
+ *min_size* items. *max-size* sets a hard limit to the size of the pool --
+ it cannot contain any more items than *max_size*, and if there are already
+ *max_size* items 'checked out' of the pool, the pool will cause any
+ greenthread calling :meth:`get` to cooperatively yield until an item
+ is :meth:`put` in.
+ """
+
+ def __init__(self, min_size=0, max_size=4, order_as_stack=False, create=None):
+ """*order_as_stack* governs the ordering of the items in the free pool.
+ If ``False`` (the default), the free items collection (of items that
+ were created and were put back in the pool) acts as a round-robin,
+ giving each item approximately equal utilization. If ``True``, the
+ free pool acts as a FILO stack, which preferentially re-uses items that
+ have most recently been used.
+ """
+ self.min_size = min_size
+ self.max_size = max_size
+ self.order_as_stack = order_as_stack
+ self.current_size = 0
+ self.channel = queue.LightQueue(0)
+ self.free_items = collections.deque()
+ if create is not None:
+ self.create = create
+
+ for x in range(min_size):
+ self.current_size += 1
+ self.free_items.append(self.create())
+
+ def get(self):
+ """Return an item from the pool, when one is available. This may
+ cause the calling greenthread to block.
+ """
+ if self.free_items:
+ return self.free_items.popleft()
+ self.current_size += 1
+ if self.current_size <= self.max_size:
+ try:
+ created = self.create()
+ except:
+ self.current_size -= 1
+ raise
+ return created
+ self.current_size -= 1 # did not create
+ return self.channel.get()
+
+ @contextmanager
+ def item(self):
+ """ Get an object out of the pool, for use with with statement.
+
+ >>> from eventlet import pools
+ >>> pool = pools.TokenPool(max_size=4)
+ >>> with pool.item() as obj:
+ ... print("got token")
+ ...
+ got token
+ >>> pool.free()
+ 4
+ """
+ obj = self.get()
+ try:
+ yield obj
+ finally:
+ self.put(obj)
+
+ def put(self, item):
+ """Put an item back into the pool, when done. This may
+ cause the putting greenthread to block.
+ """
+ if self.current_size > self.max_size:
+ self.current_size -= 1
+ return
+
+ if self.waiting():
+ try:
+ self.channel.put(item, block=False)
+ return
+ except queue.Full:
+ pass
+
+ if self.order_as_stack:
+ self.free_items.appendleft(item)
+ else:
+ self.free_items.append(item)
+
+ def resize(self, new_size):
+ """Resize the pool to *new_size*.
+
+ Adjusting this number does not affect existing items checked out of
+ the pool, nor on any greenthreads who are waiting for an item to free
+ up. Some indeterminate number of :meth:`get`/:meth:`put`
+ cycles will be necessary before the new maximum size truly matches
+ the actual operation of the pool.
+ """
+ self.max_size = new_size
+
+ def free(self):
+ """Return the number of free items in the pool. This corresponds
+ to the number of :meth:`get` calls needed to empty the pool.
+ """
+ return len(self.free_items) + self.max_size - self.current_size
+
+ def waiting(self):
+ """Return the number of routines waiting for a pool item.
+ """
+ return max(0, self.channel.getting() - self.channel.putting())
+
+ def create(self):
+ """Generate a new pool item. In order for the pool to
+ function, either this method must be overriden in a subclass
+ or the pool must be constructed with the `create` argument.
+ It accepts no arguments and returns a single instance of
+ whatever thing the pool is supposed to contain.
+
+ In general, :meth:`create` is called whenever the pool exceeds its
+ previous high-water mark of concurrently-checked-out-items. In other
+ words, in a new pool with *min_size* of 0, the very first call
+ to :meth:`get` will result in a call to :meth:`create`. If the first
+ caller calls :meth:`put` before some other caller calls :meth:`get`,
+ then the first item will be returned, and :meth:`create` will not be
+ called a second time.
+ """
+ raise NotImplementedError("Implement in subclass")
+
+
+class Token(object):
+ pass
+
+
+class TokenPool(Pool):
+ """A pool which gives out tokens (opaque unique objects), which indicate
+ that the coroutine which holds the token has a right to consume some
+ limited resource.
+ """
+
+ def create(self):
+ return Token()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/queue.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/queue.py
new file mode 100644
index 0000000000000000000000000000000000000000..b61c2f876d2ae723ea8a5e1492e94ff92c6189ee
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/queue.py
@@ -0,0 +1,492 @@
+# Copyright (c) 2009 Denis Bilenko, denis.bilenko at gmail com
+# Copyright (c) 2010 Eventlet Contributors (see AUTHORS)
+# and licensed under the MIT license:
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+"""Synchronized queues.
+
+The :mod:`eventlet.queue` module implements multi-producer, multi-consumer
+queues that work across greenlets, with the API similar to the classes found in
+the standard :mod:`Queue` and :class:`multiprocessing `
+modules.
+
+A major difference is that queues in this module operate as channels when
+initialized with *maxsize* of zero. In such case, both :meth:`Queue.empty`
+and :meth:`Queue.full` return ``True`` and :meth:`Queue.put` always blocks until
+a call to :meth:`Queue.get` retrieves the item.
+
+An interesting difference, made possible because of greenthreads, is
+that :meth:`Queue.qsize`, :meth:`Queue.empty`, and :meth:`Queue.full` *can* be
+used as indicators of whether the subsequent :meth:`Queue.get`
+or :meth:`Queue.put` will not block. The new methods :meth:`Queue.getting`
+and :meth:`Queue.putting` report on the number of greenthreads blocking
+in :meth:`put ` or :meth:`get ` respectively.
+"""
+from __future__ import print_function
+
+import sys
+import heapq
+import collections
+import traceback
+
+from eventlet.event import Event
+from eventlet.greenthread import getcurrent
+from eventlet.hubs import get_hub
+import six
+from six.moves import queue as Stdlib_Queue
+from eventlet.timeout import Timeout
+
+
+__all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'LightQueue', 'Full', 'Empty']
+
+_NONE = object()
+Full = six.moves.queue.Full
+Empty = six.moves.queue.Empty
+
+
+class Waiter(object):
+ """A low level synchronization class.
+
+ Wrapper around greenlet's ``switch()`` and ``throw()`` calls that makes them safe:
+
+ * switching will occur only if the waiting greenlet is executing :meth:`wait`
+ method currently. Otherwise, :meth:`switch` and :meth:`throw` are no-ops.
+ * any error raised in the greenlet is handled inside :meth:`switch` and :meth:`throw`
+
+ The :meth:`switch` and :meth:`throw` methods must only be called from the :class:`Hub` greenlet.
+ The :meth:`wait` method must be called from a greenlet other than :class:`Hub`.
+ """
+ __slots__ = ['greenlet']
+
+ def __init__(self):
+ self.greenlet = None
+
+ def __repr__(self):
+ if self.waiting:
+ waiting = ' waiting'
+ else:
+ waiting = ''
+ return '<%s at %s%s greenlet=%r>' % (
+ type(self).__name__, hex(id(self)), waiting, self.greenlet,
+ )
+
+ def __str__(self):
+ """
+ >>> print(Waiter())
+
+ """
+ if self.waiting:
+ waiting = ' waiting'
+ else:
+ waiting = ''
+ return '<%s%s greenlet=%s>' % (type(self).__name__, waiting, self.greenlet)
+
+ def __nonzero__(self):
+ return self.greenlet is not None
+
+ __bool__ = __nonzero__
+
+ @property
+ def waiting(self):
+ return self.greenlet is not None
+
+ def switch(self, value=None):
+ """Wake up the greenlet that is calling wait() currently (if there is one).
+ Can only be called from Hub's greenlet.
+ """
+ assert getcurrent() is get_hub(
+ ).greenlet, "Can only use Waiter.switch method from the mainloop"
+ if self.greenlet is not None:
+ try:
+ self.greenlet.switch(value)
+ except Exception:
+ traceback.print_exc()
+
+ def throw(self, *throw_args):
+ """Make greenlet calling wait() wake up (if there is a wait()).
+ Can only be called from Hub's greenlet.
+ """
+ assert getcurrent() is get_hub(
+ ).greenlet, "Can only use Waiter.switch method from the mainloop"
+ if self.greenlet is not None:
+ try:
+ self.greenlet.throw(*throw_args)
+ except Exception:
+ traceback.print_exc()
+
+ # XXX should be renamed to get() ? and the whole class is called Receiver?
+ def wait(self):
+ """Wait until switch() or throw() is called.
+ """
+ assert self.greenlet is None, 'This Waiter is already used by %r' % (self.greenlet, )
+ self.greenlet = getcurrent()
+ try:
+ return get_hub().switch()
+ finally:
+ self.greenlet = None
+
+
+class LightQueue(object):
+ """
+ This is a variant of Queue that behaves mostly like the standard
+ :class:`Stdlib_Queue`. It differs by not supporting the
+ :meth:`task_done ` or
+ :meth:`join ` methods, and is a little faster for
+ not having that overhead.
+ """
+
+ def __init__(self, maxsize=None):
+ if maxsize is None or maxsize < 0: # None is not comparable in 3.x
+ self.maxsize = None
+ else:
+ self.maxsize = maxsize
+ self.getters = set()
+ self.putters = set()
+ self._event_unlock = None
+ self._init(maxsize)
+
+ # QQQ make maxsize into a property with setter that schedules unlock if necessary
+
+ def _init(self, maxsize):
+ self.queue = collections.deque()
+
+ def _get(self):
+ return self.queue.popleft()
+
+ def _put(self, item):
+ self.queue.append(item)
+
+ def __repr__(self):
+ return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._format())
+
+ def __str__(self):
+ return '<%s %s>' % (type(self).__name__, self._format())
+
+ def _format(self):
+ result = 'maxsize=%r' % (self.maxsize, )
+ if getattr(self, 'queue', None):
+ result += ' queue=%r' % self.queue
+ if self.getters:
+ result += ' getters[%s]' % len(self.getters)
+ if self.putters:
+ result += ' putters[%s]' % len(self.putters)
+ if self._event_unlock is not None:
+ result += ' unlocking'
+ return result
+
+ def qsize(self):
+ """Return the size of the queue."""
+ return len(self.queue)
+
+ def resize(self, size):
+ """Resizes the queue's maximum size.
+
+ If the size is increased, and there are putters waiting, they may be woken up."""
+ # None is not comparable in 3.x
+ if self.maxsize is not None and (size is None or size > self.maxsize):
+ # Maybe wake some stuff up
+ self._schedule_unlock()
+ self.maxsize = size
+
+ def putting(self):
+ """Returns the number of greenthreads that are blocked waiting to put
+ items into the queue."""
+ return len(self.putters)
+
+ def getting(self):
+ """Returns the number of greenthreads that are blocked waiting on an
+ empty queue."""
+ return len(self.getters)
+
+ def empty(self):
+ """Return ``True`` if the queue is empty, ``False`` otherwise."""
+ return not self.qsize()
+
+ def full(self):
+ """Return ``True`` if the queue is full, ``False`` otherwise.
+
+ ``Queue(None)`` is never full.
+ """
+ # None is not comparable in 3.x
+ return self.maxsize is not None and self.qsize() >= self.maxsize
+
+ def put(self, item, block=True, timeout=None):
+ """Put an item into the queue.
+
+ If optional arg *block* is true and *timeout* is ``None`` (the default),
+ block if necessary until a free slot is available. If *timeout* is
+ a positive number, it blocks at most *timeout* seconds and raises
+ the :class:`Full` exception if no free slot was available within that time.
+ Otherwise (*block* is false), put an item on the queue if a free slot
+ is immediately available, else raise the :class:`Full` exception (*timeout*
+ is ignored in that case).
+ """
+ if self.maxsize is None or self.qsize() < self.maxsize:
+ # there's a free slot, put an item right away
+ self._put(item)
+ if self.getters:
+ self._schedule_unlock()
+ elif not block and get_hub().greenlet is getcurrent():
+ # we're in the mainloop, so we cannot wait; we can switch() to other greenlets though
+ # find a getter and deliver an item to it
+ while self.getters:
+ getter = self.getters.pop()
+ if getter:
+ self._put(item)
+ item = self._get()
+ getter.switch(item)
+ return
+ raise Full
+ elif block:
+ waiter = ItemWaiter(item, block)
+ self.putters.add(waiter)
+ timeout = Timeout(timeout, Full)
+ try:
+ if self.getters:
+ self._schedule_unlock()
+ result = waiter.wait()
+ assert result is waiter, "Invalid switch into Queue.put: %r" % (result, )
+ if waiter.item is not _NONE:
+ self._put(item)
+ finally:
+ timeout.cancel()
+ self.putters.discard(waiter)
+ elif self.getters:
+ waiter = ItemWaiter(item, block)
+ self.putters.add(waiter)
+ self._schedule_unlock()
+ result = waiter.wait()
+ assert result is waiter, "Invalid switch into Queue.put: %r" % (result, )
+ if waiter.item is not _NONE:
+ raise Full
+ else:
+ raise Full
+
+ def put_nowait(self, item):
+ """Put an item into the queue without blocking.
+
+ Only enqueue the item if a free slot is immediately available.
+ Otherwise raise the :class:`Full` exception.
+ """
+ self.put(item, False)
+
+ def get(self, block=True, timeout=None):
+ """Remove and return an item from the queue.
+
+ If optional args *block* is true and *timeout* is ``None`` (the default),
+ block if necessary until an item is available. If *timeout* is a positive number,
+ it blocks at most *timeout* seconds and raises the :class:`Empty` exception
+ if no item was available within that time. Otherwise (*block* is false), return
+ an item if one is immediately available, else raise the :class:`Empty` exception
+ (*timeout* is ignored in that case).
+ """
+ if self.qsize():
+ if self.putters:
+ self._schedule_unlock()
+ return self._get()
+ elif not block and get_hub().greenlet is getcurrent():
+ # special case to make get_nowait() runnable in the mainloop greenlet
+ # there are no items in the queue; try to fix the situation by unlocking putters
+ while self.putters:
+ putter = self.putters.pop()
+ if putter:
+ putter.switch(putter)
+ if self.qsize():
+ return self._get()
+ raise Empty
+ elif block:
+ waiter = Waiter()
+ timeout = Timeout(timeout, Empty)
+ try:
+ self.getters.add(waiter)
+ if self.putters:
+ self._schedule_unlock()
+ try:
+ return waiter.wait()
+ except:
+ self._schedule_unlock()
+ raise
+ finally:
+ self.getters.discard(waiter)
+ timeout.cancel()
+ else:
+ raise Empty
+
+ def get_nowait(self):
+ """Remove and return an item from the queue without blocking.
+
+ Only get an item if one is immediately available. Otherwise
+ raise the :class:`Empty` exception.
+ """
+ return self.get(False)
+
+ def _unlock(self):
+ try:
+ while True:
+ if self.qsize() and self.getters:
+ getter = self.getters.pop()
+ if getter:
+ try:
+ item = self._get()
+ except:
+ getter.throw(*sys.exc_info())
+ else:
+ getter.switch(item)
+ elif self.putters and self.getters:
+ putter = self.putters.pop()
+ if putter:
+ getter = self.getters.pop()
+ if getter:
+ item = putter.item
+ # this makes greenlet calling put() not to call _put() again
+ putter.item = _NONE
+ self._put(item)
+ item = self._get()
+ getter.switch(item)
+ putter.switch(putter)
+ else:
+ self.putters.add(putter)
+ elif self.putters and (self.getters or
+ self.maxsize is None or
+ self.qsize() < self.maxsize):
+ putter = self.putters.pop()
+ putter.switch(putter)
+ elif self.putters and not self.getters:
+ full = [p for p in self.putters if not p.block]
+ if not full:
+ break
+ for putter in full:
+ self.putters.discard(putter)
+ get_hub().schedule_call_global(
+ 0, putter.greenlet.throw, Full)
+ else:
+ break
+ finally:
+ self._event_unlock = None # QQQ maybe it's possible to obtain this info from libevent?
+ # i.e. whether this event is pending _OR_ currently executing
+ # testcase: 2 greenlets: while True: q.put(q.get()) - nothing else has a change to execute
+ # to avoid this, schedule unlock with timer(0, ...) once in a while
+
+ def _schedule_unlock(self):
+ if self._event_unlock is None:
+ self._event_unlock = get_hub().schedule_call_global(0, self._unlock)
+
+
+class ItemWaiter(Waiter):
+ __slots__ = ['item', 'block']
+
+ def __init__(self, item, block):
+ Waiter.__init__(self)
+ self.item = item
+ self.block = block
+
+
+class Queue(LightQueue):
+ '''Create a queue object with a given maximum size.
+
+ If *maxsize* is less than zero or ``None``, the queue size is infinite.
+
+ ``Queue(0)`` is a channel, that is, its :meth:`put` method always blocks
+ until the item is delivered. (This is unlike the standard
+ :class:`Stdlib_Queue`, where 0 means infinite size).
+
+ In all other respects, this Queue class resembles the standard library,
+ :class:`Stdlib_Queue`.
+ '''
+
+ def __init__(self, maxsize=None):
+ LightQueue.__init__(self, maxsize)
+ self.unfinished_tasks = 0
+ self._cond = Event()
+
+ def _format(self):
+ result = LightQueue._format(self)
+ if self.unfinished_tasks:
+ result += ' tasks=%s _cond=%s' % (self.unfinished_tasks, self._cond)
+ return result
+
+ def _put(self, item):
+ LightQueue._put(self, item)
+ self._put_bookkeeping()
+
+ def _put_bookkeeping(self):
+ self.unfinished_tasks += 1
+ if self._cond.ready():
+ self._cond.reset()
+
+ def task_done(self):
+ '''Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
+ For each :meth:`get ` used to fetch a task, a subsequent call to
+ :meth:`task_done` tells the queue that the processing on the task is complete.
+
+ If a :meth:`join` is currently blocking, it will resume when all items have been processed
+ (meaning that a :meth:`task_done` call was received for every item that had been
+ :meth:`put ` into the queue).
+
+ Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
+ '''
+
+ if self.unfinished_tasks <= 0:
+ raise ValueError('task_done() called too many times')
+ self.unfinished_tasks -= 1
+ if self.unfinished_tasks == 0:
+ self._cond.send(None)
+
+ def join(self):
+ '''Block until all items in the queue have been gotten and processed.
+
+ The count of unfinished tasks goes up whenever an item is added to the queue.
+ The count goes down whenever a consumer thread calls :meth:`task_done` to indicate
+ that the item was retrieved and all work on it is complete. When the count of
+ unfinished tasks drops to zero, :meth:`join` unblocks.
+ '''
+ if self.unfinished_tasks > 0:
+ self._cond.wait()
+
+
+class PriorityQueue(Queue):
+ '''A subclass of :class:`Queue` that retrieves entries in priority order (lowest first).
+
+ Entries are typically tuples of the form: ``(priority number, data)``.
+ '''
+
+ def _init(self, maxsize):
+ self.queue = []
+
+ def _put(self, item, heappush=heapq.heappush):
+ heappush(self.queue, item)
+ self._put_bookkeeping()
+
+ def _get(self, heappop=heapq.heappop):
+ return heappop(self.queue)
+
+
+class LifoQueue(Queue):
+ '''A subclass of :class:`Queue` that retrieves most recently added entries first.'''
+
+ def _init(self, maxsize):
+ self.queue = []
+
+ def _put(self, item):
+ self.queue.append(item)
+ self._put_bookkeeping()
+
+ def _get(self):
+ return self.queue.pop()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/semaphore.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/semaphore.py
new file mode 100644
index 0000000000000000000000000000000000000000..18b5b05f4a74aa7ff9ea81c5af9bb6bf8622b94f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/semaphore.py
@@ -0,0 +1,315 @@
+import collections
+
+import eventlet
+from eventlet import hubs
+
+
+class Semaphore(object):
+
+ """An unbounded semaphore.
+ Optionally initialize with a resource *count*, then :meth:`acquire` and
+ :meth:`release` resources as needed. Attempting to :meth:`acquire` when
+ *count* is zero suspends the calling greenthread until *count* becomes
+ nonzero again.
+
+ This is API-compatible with :class:`threading.Semaphore`.
+
+ It is a context manager, and thus can be used in a with block::
+
+ sem = Semaphore(2)
+ with sem:
+ do_some_stuff()
+
+ If not specified, *value* defaults to 1.
+
+ It is possible to limit acquire time::
+
+ sem = Semaphore()
+ ok = sem.acquire(timeout=0.1)
+ # True if acquired, False if timed out.
+
+ """
+
+ def __init__(self, value=1):
+ try:
+ value = int(value)
+ except ValueError as e:
+ msg = 'Semaphore() expect value :: int, actual: {0} {1}'.format(type(value), str(e))
+ raise TypeError(msg)
+ if value < 0:
+ msg = 'Semaphore() expect value >= 0, actual: {0}'.format(repr(value))
+ raise ValueError(msg)
+ self.counter = value
+ self._waiters = collections.deque()
+
+ def __repr__(self):
+ params = (self.__class__.__name__, hex(id(self)),
+ self.counter, len(self._waiters))
+ return '<%s at %s c=%s _w[%s]>' % params
+
+ def __str__(self):
+ params = (self.__class__.__name__, self.counter, len(self._waiters))
+ return '<%s c=%s _w[%s]>' % params
+
+ def locked(self):
+ """Returns true if a call to acquire would block.
+ """
+ return self.counter <= 0
+
+ def bounded(self):
+ """Returns False; for consistency with
+ :class:`~eventlet.semaphore.CappedSemaphore`.
+ """
+ return False
+
+ def acquire(self, blocking=True, timeout=None):
+ """Acquire a semaphore.
+
+ When invoked without arguments: if the internal counter is larger than
+ zero on entry, decrement it by one and return immediately. If it is zero
+ on entry, block, waiting until some other thread has called release() to
+ make it larger than zero. This is done with proper interlocking so that
+ if multiple acquire() calls are blocked, release() will wake exactly one
+ of them up. The implementation may pick one at random, so the order in
+ which blocked threads are awakened should not be relied on. There is no
+ return value in this case.
+
+ When invoked with blocking set to true, do the same thing as when called
+ without arguments, and return true.
+
+ When invoked with blocking set to false, do not block. If a call without
+ an argument would block, return false immediately; otherwise, do the
+ same thing as when called without arguments, and return true.
+
+ Timeout value must be strictly positive.
+ """
+ if timeout == -1:
+ timeout = None
+ if timeout is not None and timeout < 0:
+ raise ValueError("timeout value must be strictly positive")
+ if not blocking:
+ if timeout is not None:
+ raise ValueError("can't specify timeout for non-blocking acquire")
+ timeout = 0
+ if not blocking and self.locked():
+ return False
+
+ current_thread = eventlet.getcurrent()
+
+ if self.counter <= 0 or self._waiters:
+ if current_thread not in self._waiters:
+ self._waiters.append(current_thread)
+ try:
+ if timeout is not None:
+ ok = False
+ with eventlet.Timeout(timeout, False):
+ while self.counter <= 0:
+ hubs.get_hub().switch()
+ ok = True
+ if not ok:
+ return False
+ else:
+ # If someone else is already in this wait loop, give them
+ # a chance to get out.
+ while True:
+ hubs.get_hub().switch()
+ if self.counter > 0:
+ break
+ finally:
+ try:
+ self._waiters.remove(current_thread)
+ except ValueError:
+ # Fine if its already been dropped.
+ pass
+
+ self.counter -= 1
+ return True
+
+ def __enter__(self):
+ self.acquire()
+
+ def release(self, blocking=True):
+ """Release a semaphore, incrementing the internal counter by one. When
+ it was zero on entry and another thread is waiting for it to become
+ larger than zero again, wake up that thread.
+
+ The *blocking* argument is for consistency with CappedSemaphore and is
+ ignored
+ """
+ self.counter += 1
+ if self._waiters:
+ hubs.get_hub().schedule_call_global(0, self._do_acquire)
+ return True
+
+ def _do_acquire(self):
+ if self._waiters and self.counter > 0:
+ waiter = self._waiters.popleft()
+ waiter.switch()
+
+ def __exit__(self, typ, val, tb):
+ self.release()
+
+ @property
+ def balance(self):
+ """An integer value that represents how many new calls to
+ :meth:`acquire` or :meth:`release` would be needed to get the counter to
+ 0. If it is positive, then its value is the number of acquires that can
+ happen before the next acquire would block. If it is negative, it is
+ the negative of the number of releases that would be required in order
+ to make the counter 0 again (one more release would push the counter to
+ 1 and unblock acquirers). It takes into account how many greenthreads
+ are currently blocking in :meth:`acquire`.
+ """
+ # positive means there are free items
+ # zero means there are no free items but nobody has requested one
+ # negative means there are requests for items, but no items
+ return self.counter - len(self._waiters)
+
+
+class BoundedSemaphore(Semaphore):
+
+ """A bounded semaphore checks to make sure its current value doesn't exceed
+ its initial value. If it does, ValueError is raised. In most situations
+ semaphores are used to guard resources with limited capacity. If the
+ semaphore is released too many times it's a sign of a bug. If not given,
+ *value* defaults to 1.
+ """
+
+ def __init__(self, value=1):
+ super(BoundedSemaphore, self).__init__(value)
+ self.original_counter = value
+
+ def release(self, blocking=True):
+ """Release a semaphore, incrementing the internal counter by one. If
+ the counter would exceed the initial value, raises ValueError. When
+ it was zero on entry and another thread is waiting for it to become
+ larger than zero again, wake up that thread.
+
+ The *blocking* argument is for consistency with :class:`CappedSemaphore`
+ and is ignored
+ """
+ if self.counter >= self.original_counter:
+ raise ValueError("Semaphore released too many times")
+ return super(BoundedSemaphore, self).release(blocking)
+
+
+class CappedSemaphore(object):
+
+ """A blockingly bounded semaphore.
+
+ Optionally initialize with a resource *count*, then :meth:`acquire` and
+ :meth:`release` resources as needed. Attempting to :meth:`acquire` when
+ *count* is zero suspends the calling greenthread until count becomes nonzero
+ again. Attempting to :meth:`release` after *count* has reached *limit*
+ suspends the calling greenthread until *count* becomes less than *limit*
+ again.
+
+ This has the same API as :class:`threading.Semaphore`, though its
+ semantics and behavior differ subtly due to the upper limit on calls
+ to :meth:`release`. It is **not** compatible with
+ :class:`threading.BoundedSemaphore` because it blocks when reaching *limit*
+ instead of raising a ValueError.
+
+ It is a context manager, and thus can be used in a with block::
+
+ sem = CappedSemaphore(2)
+ with sem:
+ do_some_stuff()
+ """
+
+ def __init__(self, count, limit):
+ if count < 0:
+ raise ValueError("CappedSemaphore must be initialized with a "
+ "positive number, got %s" % count)
+ if count > limit:
+ # accidentally, this also catches the case when limit is None
+ raise ValueError("'count' cannot be more than 'limit'")
+ self.lower_bound = Semaphore(count)
+ self.upper_bound = Semaphore(limit - count)
+
+ def __repr__(self):
+ params = (self.__class__.__name__, hex(id(self)),
+ self.balance, self.lower_bound, self.upper_bound)
+ return '<%s at %s b=%s l=%s u=%s>' % params
+
+ def __str__(self):
+ params = (self.__class__.__name__, self.balance,
+ self.lower_bound, self.upper_bound)
+ return '<%s b=%s l=%s u=%s>' % params
+
+ def locked(self):
+ """Returns true if a call to acquire would block.
+ """
+ return self.lower_bound.locked()
+
+ def bounded(self):
+ """Returns true if a call to release would block.
+ """
+ return self.upper_bound.locked()
+
+ def acquire(self, blocking=True):
+ """Acquire a semaphore.
+
+ When invoked without arguments: if the internal counter is larger than
+ zero on entry, decrement it by one and return immediately. If it is zero
+ on entry, block, waiting until some other thread has called release() to
+ make it larger than zero. This is done with proper interlocking so that
+ if multiple acquire() calls are blocked, release() will wake exactly one
+ of them up. The implementation may pick one at random, so the order in
+ which blocked threads are awakened should not be relied on. There is no
+ return value in this case.
+
+ When invoked with blocking set to true, do the same thing as when called
+ without arguments, and return true.
+
+ When invoked with blocking set to false, do not block. If a call without
+ an argument would block, return false immediately; otherwise, do the
+ same thing as when called without arguments, and return true.
+ """
+ if not blocking and self.locked():
+ return False
+ self.upper_bound.release()
+ try:
+ return self.lower_bound.acquire()
+ except:
+ self.upper_bound.counter -= 1
+ # using counter directly means that it can be less than zero.
+ # however I certainly don't need to wait here and I don't seem to have
+ # a need to care about such inconsistency
+ raise
+
+ def __enter__(self):
+ self.acquire()
+
+ def release(self, blocking=True):
+ """Release a semaphore. In this class, this behaves very much like
+ an :meth:`acquire` but in the opposite direction.
+
+ Imagine the docs of :meth:`acquire` here, but with every direction
+ reversed. When calling this method, it will block if the internal
+ counter is greater than or equal to *limit*.
+ """
+ if not blocking and self.bounded():
+ return False
+ self.lower_bound.release()
+ try:
+ return self.upper_bound.acquire()
+ except:
+ self.lower_bound.counter -= 1
+ raise
+
+ def __exit__(self, typ, val, tb):
+ self.release()
+
+ @property
+ def balance(self):
+ """An integer value that represents how many new calls to
+ :meth:`acquire` or :meth:`release` would be needed to get the counter to
+ 0. If it is positive, then its value is the number of acquires that can
+ happen before the next acquire would block. If it is negative, it is
+ the negative of the number of releases that would be required in order
+ to make the counter 0 again (one more release would push the counter to
+ 1 and unblock acquirers). It takes into account how many greenthreads
+ are currently blocking in :meth:`acquire` and :meth:`release`.
+ """
+ return self.lower_bound.balance - self.upper_bound.balance
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/timeout.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/timeout.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ab893eef6287ba8bcac871c6c9c348fc063a57e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/timeout.py
@@ -0,0 +1,184 @@
+# Copyright (c) 2009-2010 Denis Bilenko, denis.bilenko at gmail com
+# Copyright (c) 2010 Eventlet Contributors (see AUTHORS)
+# and licensed under the MIT license:
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import functools
+import inspect
+
+import eventlet
+from eventlet.support import greenlets as greenlet
+from eventlet.hubs import get_hub
+
+__all__ = ['Timeout', 'with_timeout', 'wrap_is_timeout', 'is_timeout']
+
+_MISSING = object()
+
+# deriving from BaseException so that "except Exception as e" doesn't catch
+# Timeout exceptions.
+
+
+class Timeout(BaseException):
+ """Raises *exception* in the current greenthread after *timeout* seconds.
+
+ When *exception* is omitted or ``None``, the :class:`Timeout` instance
+ itself is raised. If *seconds* is None, the timer is not scheduled, and is
+ only useful if you're planning to raise it directly.
+
+ Timeout objects are context managers, and so can be used in with statements.
+ When used in a with statement, if *exception* is ``False``, the timeout is
+ still raised, but the context manager suppresses it, so the code outside the
+ with-block won't see it.
+ """
+
+ def __init__(self, seconds=None, exception=None):
+ self.seconds = seconds
+ self.exception = exception
+ self.timer = None
+ self.start()
+
+ def start(self):
+ """Schedule the timeout. This is called on construction, so
+ it should not be called explicitly, unless the timer has been
+ canceled."""
+ assert not self.pending, \
+ '%r is already started; to restart it, cancel it first' % self
+ if self.seconds is None: # "fake" timeout (never expires)
+ self.timer = None
+ elif self.exception is None or isinstance(self.exception, bool): # timeout that raises self
+ self.timer = get_hub().schedule_call_global(
+ self.seconds, greenlet.getcurrent().throw, self)
+ else: # regular timeout with user-provided exception
+ self.timer = get_hub().schedule_call_global(
+ self.seconds, greenlet.getcurrent().throw, self.exception)
+ return self
+
+ @property
+ def pending(self):
+ """True if the timeout is scheduled to be raised."""
+ if self.timer is not None:
+ return self.timer.pending
+ else:
+ return False
+
+ def cancel(self):
+ """If the timeout is pending, cancel it. If not using
+ Timeouts in ``with`` statements, always call cancel() in a
+ ``finally`` after the block of code that is getting timed out.
+ If not canceled, the timeout will be raised later on, in some
+ unexpected section of the application."""
+ if self.timer is not None:
+ self.timer.cancel()
+ self.timer = None
+
+ def __repr__(self):
+ classname = self.__class__.__name__
+ if self.pending:
+ pending = ' pending'
+ else:
+ pending = ''
+ if self.exception is None:
+ exception = ''
+ else:
+ exception = ' exception=%r' % self.exception
+ return '<%s at %s seconds=%s%s%s>' % (
+ classname, hex(id(self)), self.seconds, exception, pending)
+
+ def __str__(self):
+ """
+ >>> raise Timeout # doctest: +IGNORE_EXCEPTION_DETAIL
+ Traceback (most recent call last):
+ ...
+ Timeout
+ """
+ if self.seconds is None:
+ return ''
+ if self.seconds == 1:
+ suffix = ''
+ else:
+ suffix = 's'
+ if self.exception is None or self.exception is True:
+ return '%s second%s' % (self.seconds, suffix)
+ elif self.exception is False:
+ return '%s second%s (silent)' % (self.seconds, suffix)
+ else:
+ return '%s second%s (%s)' % (self.seconds, suffix, self.exception)
+
+ def __enter__(self):
+ if self.timer is None:
+ self.start()
+ return self
+
+ def __exit__(self, typ, value, tb):
+ self.cancel()
+ if value is self and self.exception is False:
+ return True
+
+ @property
+ def is_timeout(self):
+ return True
+
+
+def with_timeout(seconds, function, *args, **kwds):
+ """Wrap a call to some (yielding) function with a timeout; if the called
+ function fails to return before the timeout, cancel it and return a flag
+ value.
+ """
+ timeout_value = kwds.pop("timeout_value", _MISSING)
+ timeout = Timeout(seconds)
+ try:
+ try:
+ return function(*args, **kwds)
+ except Timeout as ex:
+ if ex is timeout and timeout_value is not _MISSING:
+ return timeout_value
+ raise
+ finally:
+ timeout.cancel()
+
+
+def wrap_is_timeout(base):
+ '''Adds `.is_timeout=True` attribute to objects returned by `base()`.
+
+ When `base` is class, attribute is added as read-only property. Returns `base`.
+ Otherwise, it returns a function that sets attribute on result of `base()` call.
+
+ Wrappers make best effort to be transparent.
+ '''
+ if inspect.isclass(base):
+ base.is_timeout = property(lambda _: True)
+ return base
+
+ @functools.wraps(base)
+ def fun(*args, **kwargs):
+ ex = base(*args, **kwargs)
+ ex.is_timeout = True
+ return ex
+ return fun
+
+
+if isinstance(__builtins__, dict): # seen when running tests on py310, but HOW??
+ _timeout_err = __builtins__.get('TimeoutError', Timeout)
+else:
+ _timeout_err = getattr(__builtins__, 'TimeoutError', Timeout)
+
+
+def is_timeout(obj):
+ return bool(getattr(obj, 'is_timeout', False)) or isinstance(obj, _timeout_err)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/tpool.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/tpool.py
new file mode 100644
index 0000000000000000000000000000000000000000..af5e8959d3728afb77e5c3afa37591efa899f783
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/tpool.py
@@ -0,0 +1,343 @@
+# Copyright (c) 2007-2009, Linden Research, Inc.
+# Copyright (c) 2007, IBM Corp.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import atexit
+try:
+ import _imp as imp
+except ImportError:
+ import imp
+import os
+import sys
+import traceback
+
+import eventlet
+from eventlet import event, greenio, greenthread, patcher, timeout
+import six
+
+__all__ = ['execute', 'Proxy', 'killall', 'set_num_threads']
+
+
+EXC_CLASSES = (Exception, timeout.Timeout)
+SYS_EXCS = (GeneratorExit, KeyboardInterrupt, SystemExit)
+
+QUIET = True
+
+socket = patcher.original('socket')
+threading = patcher.original('threading')
+if six.PY2:
+ Queue_module = patcher.original('Queue')
+if six.PY3:
+ Queue_module = patcher.original('queue')
+
+Empty = Queue_module.Empty
+Queue = Queue_module.Queue
+
+_bytetosend = b' '
+_coro = None
+_nthreads = int(os.environ.get('EVENTLET_THREADPOOL_SIZE', 20))
+_reqq = _rspq = None
+_rsock = _wsock = None
+_setup_already = False
+_threads = []
+
+
+def tpool_trampoline():
+ global _rspq
+ while True:
+ try:
+ _c = _rsock.recv(1)
+ assert _c
+ # FIXME: this is probably redundant since using sockets instead of pipe now
+ except ValueError:
+ break # will be raised when pipe is closed
+ while not _rspq.empty():
+ try:
+ (e, rv) = _rspq.get(block=False)
+ e.send(rv)
+ e = rv = None
+ except Empty:
+ pass
+
+
+def tworker():
+ global _rspq
+ while True:
+ try:
+ msg = _reqq.get()
+ except AttributeError:
+ return # can't get anything off of a dud queue
+ if msg is None:
+ return
+ (e, meth, args, kwargs) = msg
+ rv = None
+ try:
+ rv = meth(*args, **kwargs)
+ except SYS_EXCS:
+ raise
+ except EXC_CLASSES:
+ rv = sys.exc_info()
+ if sys.version_info >= (3, 4):
+ traceback.clear_frames(rv[1].__traceback__)
+ if six.PY2:
+ sys.exc_clear()
+ # test_leakage_from_tracebacks verifies that the use of
+ # exc_info does not lead to memory leaks
+ _rspq.put((e, rv))
+ msg = meth = args = kwargs = e = rv = None
+ _wsock.sendall(_bytetosend)
+
+
+def execute(meth, *args, **kwargs):
+ """
+ Execute *meth* in a Python thread, blocking the current coroutine/
+ greenthread until the method completes.
+
+ The primary use case for this is to wrap an object or module that is not
+ amenable to monkeypatching or any of the other tricks that Eventlet uses
+ to achieve cooperative yielding. With tpool, you can force such objects to
+ cooperate with green threads by sticking them in native threads, at the cost
+ of some overhead.
+ """
+ setup()
+ # if already in tpool, don't recurse into the tpool
+ # also, call functions directly if we're inside an import lock, because
+ # if meth does any importing (sadly common), it will hang
+ my_thread = threading.current_thread()
+ if my_thread in _threads or imp.lock_held() or _nthreads == 0:
+ return meth(*args, **kwargs)
+
+ e = event.Event()
+ _reqq.put((e, meth, args, kwargs))
+
+ rv = e.wait()
+ if isinstance(rv, tuple) \
+ and len(rv) == 3 \
+ and isinstance(rv[1], EXC_CLASSES):
+ (c, e, tb) = rv
+ if not QUIET:
+ traceback.print_exception(c, e, tb)
+ traceback.print_stack()
+ six.reraise(c, e, tb)
+ return rv
+
+
+def proxy_call(autowrap, f, *args, **kwargs):
+ """
+ Call a function *f* and returns the value. If the type of the return value
+ is in the *autowrap* collection, then it is wrapped in a :class:`Proxy`
+ object before return.
+
+ Normally *f* will be called in the threadpool with :func:`execute`; if the
+ keyword argument "nonblocking" is set to ``True``, it will simply be
+ executed directly. This is useful if you have an object which has methods
+ that don't need to be called in a separate thread, but which return objects
+ that should be Proxy wrapped.
+ """
+ if kwargs.pop('nonblocking', False):
+ rv = f(*args, **kwargs)
+ else:
+ rv = execute(f, *args, **kwargs)
+ if isinstance(rv, autowrap):
+ return Proxy(rv, autowrap)
+ else:
+ return rv
+
+
+class Proxy(object):
+ """
+ a simple proxy-wrapper of any object that comes with a
+ methods-only interface, in order to forward every method
+ invocation onto a thread in the native-thread pool. A key
+ restriction is that the object's methods should not switch
+ greenlets or use Eventlet primitives, since they are in a
+ different thread from the main hub, and therefore might behave
+ unexpectedly. This is for running native-threaded code
+ only.
+
+ It's common to want to have some of the attributes or return
+ values also wrapped in Proxy objects (for example, database
+ connection objects produce cursor objects which also should be
+ wrapped in Proxy objects to remain nonblocking). *autowrap*, if
+ supplied, is a collection of types; if an attribute or return
+ value matches one of those types (via isinstance), it will be
+ wrapped in a Proxy. *autowrap_names* is a collection
+ of strings, which represent the names of attributes that should be
+ wrapped in Proxy objects when accessed.
+ """
+
+ def __init__(self, obj, autowrap=(), autowrap_names=()):
+ self._obj = obj
+ self._autowrap = autowrap
+ self._autowrap_names = autowrap_names
+
+ def __getattr__(self, attr_name):
+ f = getattr(self._obj, attr_name)
+ if not hasattr(f, '__call__'):
+ if isinstance(f, self._autowrap) or attr_name in self._autowrap_names:
+ return Proxy(f, self._autowrap)
+ return f
+
+ def doit(*args, **kwargs):
+ result = proxy_call(self._autowrap, f, *args, **kwargs)
+ if attr_name in self._autowrap_names and not isinstance(result, Proxy):
+ return Proxy(result)
+ return result
+ return doit
+
+ # the following are a buncha methods that the python interpeter
+ # doesn't use getattr to retrieve and therefore have to be defined
+ # explicitly
+ def __getitem__(self, key):
+ return proxy_call(self._autowrap, self._obj.__getitem__, key)
+
+ def __setitem__(self, key, value):
+ return proxy_call(self._autowrap, self._obj.__setitem__, key, value)
+
+ def __deepcopy__(self, memo=None):
+ return proxy_call(self._autowrap, self._obj.__deepcopy__, memo)
+
+ def __copy__(self, memo=None):
+ return proxy_call(self._autowrap, self._obj.__copy__, memo)
+
+ def __call__(self, *a, **kw):
+ if '__call__' in self._autowrap_names:
+ return Proxy(proxy_call(self._autowrap, self._obj, *a, **kw))
+ else:
+ return proxy_call(self._autowrap, self._obj, *a, **kw)
+
+ def __enter__(self):
+ return proxy_call(self._autowrap, self._obj.__enter__)
+
+ def __exit__(self, *exc):
+ return proxy_call(self._autowrap, self._obj.__exit__, *exc)
+
+ # these don't go through a proxy call, because they're likely to
+ # be called often, and are unlikely to be implemented on the
+ # wrapped object in such a way that they would block
+ def __eq__(self, rhs):
+ return self._obj == rhs
+
+ def __hash__(self):
+ return self._obj.__hash__()
+
+ def __repr__(self):
+ return self._obj.__repr__()
+
+ def __str__(self):
+ return self._obj.__str__()
+
+ def __len__(self):
+ return len(self._obj)
+
+ def __nonzero__(self):
+ return bool(self._obj)
+ # Python3
+ __bool__ = __nonzero__
+
+ def __iter__(self):
+ it = iter(self._obj)
+ if it == self._obj:
+ return self
+ else:
+ return Proxy(it)
+
+ def next(self):
+ return proxy_call(self._autowrap, next, self._obj)
+ # Python3
+ __next__ = next
+
+
+def setup():
+ global _rsock, _wsock, _coro, _setup_already, _rspq, _reqq
+ if _setup_already:
+ return
+ else:
+ _setup_already = True
+
+ assert _nthreads >= 0, "Can't specify negative number of threads"
+ if _nthreads == 0:
+ import warnings
+ warnings.warn("Zero threads in tpool. All tpool.execute calls will\
+ execute in main thread. Check the value of the environment \
+ variable EVENTLET_THREADPOOL_SIZE.", RuntimeWarning)
+ _reqq = Queue(maxsize=-1)
+ _rspq = Queue(maxsize=-1)
+
+ # connected socket pair
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.bind(('127.0.0.1', 0))
+ sock.listen(1)
+ csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ csock.connect(sock.getsockname())
+ csock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
+ _wsock, _addr = sock.accept()
+ _wsock.settimeout(None)
+ _wsock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
+ sock.close()
+ _rsock = greenio.GreenSocket(csock)
+ _rsock.settimeout(None)
+
+ for i in six.moves.range(_nthreads):
+ t = threading.Thread(target=tworker,
+ name="tpool_thread_%s" % i)
+ t.daemon = True
+ t.start()
+ _threads.append(t)
+
+ _coro = greenthread.spawn_n(tpool_trampoline)
+ # This yield fixes subtle error with GreenSocket.__del__
+ eventlet.sleep(0)
+
+
+# Avoid ResourceWarning unclosed socket on Python3.2+
+@atexit.register
+def killall():
+ global _setup_already, _rspq, _rsock, _wsock
+ if not _setup_already:
+ return
+
+ # This yield fixes freeze in some scenarios
+ eventlet.sleep(0)
+
+ for thr in _threads:
+ _reqq.put(None)
+ for thr in _threads:
+ thr.join()
+ del _threads[:]
+
+ # return any remaining results
+ while (_rspq is not None) and not _rspq.empty():
+ try:
+ (e, rv) = _rspq.get(block=False)
+ e.send(rv)
+ e = rv = None
+ except Empty:
+ pass
+
+ if _coro is not None:
+ greenthread.kill(_coro)
+ if _rsock is not None:
+ _rsock.close()
+ _rsock = None
+ if _wsock is not None:
+ _wsock.close()
+ _wsock = None
+ _rspq = None
+ _setup_already = False
+
+
+def set_num_threads(nthreads):
+ global _nthreads
+ _nthreads = nthreads
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/websocket.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/websocket.py
new file mode 100644
index 0000000000000000000000000000000000000000..01245b8093eed78d35a59d26531097a3aa6f590f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/websocket.py
@@ -0,0 +1,864 @@
+import base64
+import codecs
+import collections
+import errno
+from random import Random
+from socket import error as SocketError
+import string
+import struct
+import sys
+import time
+
+import zlib
+
+try:
+ from hashlib import md5, sha1
+except ImportError: # pragma NO COVER
+ from md5 import md5
+ from sha import sha as sha1
+
+from eventlet import semaphore
+from eventlet import wsgi
+from eventlet.green import socket
+from eventlet.support import get_errno
+import six
+
+# Python 2's utf8 decoding is more lenient than we'd like
+# In order to pass autobahn's testsuite we need stricter validation
+# if available...
+for _mod in ('wsaccel.utf8validator', 'autobahn.utf8validator'):
+ # autobahn has it's own python-based validator. in newest versions
+ # this prefers to use wsaccel, a cython based implementation, if available.
+ # wsaccel may also be installed w/out autobahn, or with a earlier version.
+ try:
+ utf8validator = __import__(_mod, {}, {}, [''])
+ except ImportError:
+ utf8validator = None
+ else:
+ break
+
+ACCEPTABLE_CLIENT_ERRORS = set((errno.ECONNRESET, errno.EPIPE))
+DEFAULT_MAX_FRAME_LENGTH = 8 << 20
+
+__all__ = ["WebSocketWSGI", "WebSocket"]
+PROTOCOL_GUID = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
+VALID_CLOSE_STATUS = set(
+ list(range(1000, 1004)) +
+ list(range(1007, 1012)) +
+ # 3000-3999: reserved for use by libraries, frameworks,
+ # and applications
+ list(range(3000, 4000)) +
+ # 4000-4999: reserved for private use and thus can't
+ # be registered
+ list(range(4000, 5000))
+)
+
+
+class BadRequest(Exception):
+ def __init__(self, status='400 Bad Request', body=None, headers=None):
+ super(Exception, self).__init__()
+ self.status = status
+ self.body = body
+ self.headers = headers
+
+
+class WebSocketWSGI(object):
+ """Wraps a websocket handler function in a WSGI application.
+
+ Use it like this::
+
+ @websocket.WebSocketWSGI
+ def my_handler(ws):
+ from_browser = ws.wait()
+ ws.send("from server")
+
+ The single argument to the function will be an instance of
+ :class:`WebSocket`. To close the socket, simply return from the
+ function. Note that the server will log the websocket request at
+ the time of closure.
+
+ An optional argument max_frame_length can be given, which will set the
+ maximum incoming *uncompressed* payload length of a frame. By default, this
+ is set to 8MiB. Note that excessive values here might create a DOS attack
+ vector.
+ """
+
+ def __init__(self, handler, max_frame_length=DEFAULT_MAX_FRAME_LENGTH):
+ self.handler = handler
+ self.protocol_version = None
+ self.support_legacy_versions = True
+ self.supported_protocols = []
+ self.origin_checker = None
+ self.max_frame_length = max_frame_length
+
+ @classmethod
+ def configured(cls,
+ handler=None,
+ supported_protocols=None,
+ origin_checker=None,
+ support_legacy_versions=False):
+ def decorator(handler):
+ inst = cls(handler)
+ inst.support_legacy_versions = support_legacy_versions
+ inst.origin_checker = origin_checker
+ if supported_protocols:
+ inst.supported_protocols = supported_protocols
+ return inst
+ if handler is None:
+ return decorator
+ return decorator(handler)
+
+ def __call__(self, environ, start_response):
+ http_connection_parts = [
+ part.strip()
+ for part in environ.get('HTTP_CONNECTION', '').lower().split(',')]
+ if not ('upgrade' in http_connection_parts and
+ environ.get('HTTP_UPGRADE', '').lower() == 'websocket'):
+ # need to check a few more things here for true compliance
+ start_response('400 Bad Request', [('Connection', 'close')])
+ return []
+
+ try:
+ if 'HTTP_SEC_WEBSOCKET_VERSION' in environ:
+ ws = self._handle_hybi_request(environ)
+ elif self.support_legacy_versions:
+ ws = self._handle_legacy_request(environ)
+ else:
+ raise BadRequest()
+ except BadRequest as e:
+ status = e.status
+ body = e.body or b''
+ headers = e.headers or []
+ start_response(status,
+ [('Connection', 'close'), ] + headers)
+ return [body]
+
+ try:
+ self.handler(ws)
+ except socket.error as e:
+ if get_errno(e) not in ACCEPTABLE_CLIENT_ERRORS:
+ raise
+ # Make sure we send the closing frame
+ ws._send_closing_frame(True)
+ # use this undocumented feature of eventlet.wsgi to ensure that it
+ # doesn't barf on the fact that we didn't call start_response
+ wsgi.WSGI_LOCAL.already_handled = True
+ return []
+
+ def _handle_legacy_request(self, environ):
+ if 'eventlet.input' in environ:
+ sock = environ['eventlet.input'].get_socket()
+ elif 'gunicorn.socket' in environ:
+ sock = environ['gunicorn.socket']
+ else:
+ raise Exception('No eventlet.input or gunicorn.socket present in environ.')
+
+ if 'HTTP_SEC_WEBSOCKET_KEY1' in environ:
+ self.protocol_version = 76
+ if 'HTTP_SEC_WEBSOCKET_KEY2' not in environ:
+ raise BadRequest()
+ else:
+ self.protocol_version = 75
+
+ if self.protocol_version == 76:
+ key1 = self._extract_number(environ['HTTP_SEC_WEBSOCKET_KEY1'])
+ key2 = self._extract_number(environ['HTTP_SEC_WEBSOCKET_KEY2'])
+ # There's no content-length header in the request, but it has 8
+ # bytes of data.
+ environ['wsgi.input'].content_length = 8
+ key3 = environ['wsgi.input'].read(8)
+ key = struct.pack(">II", key1, key2) + key3
+ response = md5(key).digest()
+
+ # Start building the response
+ scheme = 'ws'
+ if environ.get('wsgi.url_scheme') == 'https':
+ scheme = 'wss'
+ location = '%s://%s%s%s' % (
+ scheme,
+ environ.get('HTTP_HOST'),
+ environ.get('SCRIPT_NAME'),
+ environ.get('PATH_INFO')
+ )
+ qs = environ.get('QUERY_STRING')
+ if qs is not None:
+ location += '?' + qs
+ if self.protocol_version == 75:
+ handshake_reply = (
+ b"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
+ b"Upgrade: WebSocket\r\n"
+ b"Connection: Upgrade\r\n"
+ b"WebSocket-Origin: " + six.b(environ.get('HTTP_ORIGIN')) + b"\r\n"
+ b"WebSocket-Location: " + six.b(location) + b"\r\n\r\n"
+ )
+ elif self.protocol_version == 76:
+ handshake_reply = (
+ b"HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
+ b"Upgrade: WebSocket\r\n"
+ b"Connection: Upgrade\r\n"
+ b"Sec-WebSocket-Origin: " + six.b(environ.get('HTTP_ORIGIN')) + b"\r\n"
+ b"Sec-WebSocket-Protocol: " +
+ six.b(environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', 'default')) + b"\r\n"
+ b"Sec-WebSocket-Location: " + six.b(location) + b"\r\n"
+ b"\r\n" + response
+ )
+ else: # pragma NO COVER
+ raise ValueError("Unknown WebSocket protocol version.")
+ sock.sendall(handshake_reply)
+ return WebSocket(sock, environ, self.protocol_version)
+
+ def _parse_extension_header(self, header):
+ if header is None:
+ return None
+ res = {}
+ for ext in header.split(","):
+ parts = ext.split(";")
+ config = {}
+ for part in parts[1:]:
+ key_val = part.split("=")
+ if len(key_val) == 1:
+ config[key_val[0].strip().lower()] = True
+ else:
+ config[key_val[0].strip().lower()] = key_val[1].strip().strip('"').lower()
+ res.setdefault(parts[0].strip().lower(), []).append(config)
+ return res
+
+ def _negotiate_permessage_deflate(self, extensions):
+ if not extensions:
+ return None
+ deflate = extensions.get("permessage-deflate")
+ if deflate is None:
+ return None
+ for config in deflate:
+ # We'll evaluate each config in the client's preferred order and pick
+ # the first that we can support.
+ want_config = {
+ # These are bool options, we can support both
+ "server_no_context_takeover": config.get("server_no_context_takeover", False),
+ "client_no_context_takeover": config.get("client_no_context_takeover", False)
+ }
+ # These are either bool OR int options. True means the client can accept a value
+ # for the option, a number means the client wants that specific value.
+ max_wbits = min(zlib.MAX_WBITS, 15)
+ mwb = config.get("server_max_window_bits")
+ if mwb is not None:
+ if mwb is True:
+ want_config["server_max_window_bits"] = max_wbits
+ else:
+ want_config["server_max_window_bits"] = \
+ int(config.get("server_max_window_bits", max_wbits))
+ if not (8 <= want_config["server_max_window_bits"] <= 15):
+ continue
+ mwb = config.get("client_max_window_bits")
+ if mwb is not None:
+ if mwb is True:
+ want_config["client_max_window_bits"] = max_wbits
+ else:
+ want_config["client_max_window_bits"] = \
+ int(config.get("client_max_window_bits", max_wbits))
+ if not (8 <= want_config["client_max_window_bits"] <= 15):
+ continue
+ return want_config
+ return None
+
+ def _format_extension_header(self, parsed_extensions):
+ if not parsed_extensions:
+ return None
+ parts = []
+ for name, config in parsed_extensions.items():
+ ext_parts = [six.b(name)]
+ for key, value in config.items():
+ if value is False:
+ pass
+ elif value is True:
+ ext_parts.append(six.b(key))
+ else:
+ ext_parts.append(six.b("%s=%s" % (key, str(value))))
+ parts.append(b"; ".join(ext_parts))
+ return b", ".join(parts)
+
+ def _handle_hybi_request(self, environ):
+ if 'eventlet.input' in environ:
+ sock = environ['eventlet.input'].get_socket()
+ elif 'gunicorn.socket' in environ:
+ sock = environ['gunicorn.socket']
+ else:
+ raise Exception('No eventlet.input or gunicorn.socket present in environ.')
+
+ hybi_version = environ['HTTP_SEC_WEBSOCKET_VERSION']
+ if hybi_version not in ('8', '13', ):
+ raise BadRequest(status='426 Upgrade Required',
+ headers=[('Sec-WebSocket-Version', '8, 13')])
+ self.protocol_version = int(hybi_version)
+ if 'HTTP_SEC_WEBSOCKET_KEY' not in environ:
+ # That's bad.
+ raise BadRequest()
+ origin = environ.get(
+ 'HTTP_ORIGIN',
+ (environ.get('HTTP_SEC_WEBSOCKET_ORIGIN', '')
+ if self.protocol_version <= 8 else ''))
+ if self.origin_checker is not None:
+ if not self.origin_checker(environ.get('HTTP_HOST'), origin):
+ raise BadRequest(status='403 Forbidden')
+ protocols = environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', None)
+ negotiated_protocol = None
+ if protocols:
+ for p in (i.strip() for i in protocols.split(',')):
+ if p in self.supported_protocols:
+ negotiated_protocol = p
+ break
+
+ key = environ['HTTP_SEC_WEBSOCKET_KEY']
+ response = base64.b64encode(sha1(six.b(key) + PROTOCOL_GUID).digest())
+ handshake_reply = [b"HTTP/1.1 101 Switching Protocols",
+ b"Upgrade: websocket",
+ b"Connection: Upgrade",
+ b"Sec-WebSocket-Accept: " + response]
+ if negotiated_protocol:
+ handshake_reply.append(b"Sec-WebSocket-Protocol: " + six.b(negotiated_protocol))
+
+ parsed_extensions = {}
+ extensions = self._parse_extension_header(environ.get("HTTP_SEC_WEBSOCKET_EXTENSIONS"))
+
+ deflate = self._negotiate_permessage_deflate(extensions)
+ if deflate is not None:
+ parsed_extensions["permessage-deflate"] = deflate
+
+ formatted_ext = self._format_extension_header(parsed_extensions)
+ if formatted_ext is not None:
+ handshake_reply.append(b"Sec-WebSocket-Extensions: " + formatted_ext)
+
+ sock.sendall(b'\r\n'.join(handshake_reply) + b'\r\n\r\n')
+ return RFC6455WebSocket(sock, environ, self.protocol_version,
+ protocol=negotiated_protocol,
+ extensions=parsed_extensions,
+ max_frame_length=self.max_frame_length)
+
+ def _extract_number(self, value):
+ """
+ Utility function which, given a string like 'g98sd 5[]221@1', will
+ return 9852211. Used to parse the Sec-WebSocket-Key headers.
+ """
+ out = ""
+ spaces = 0
+ for char in value:
+ if char in string.digits:
+ out += char
+ elif char == " ":
+ spaces += 1
+ return int(out) // spaces
+
+
+class WebSocket(object):
+ """A websocket object that handles the details of
+ serialization/deserialization to the socket.
+
+ The primary way to interact with a :class:`WebSocket` object is to
+ call :meth:`send` and :meth:`wait` in order to pass messages back
+ and forth with the browser. Also available are the following
+ properties:
+
+ path
+ The path value of the request. This is the same as the WSGI PATH_INFO variable,
+ but more convenient.
+ protocol
+ The value of the Websocket-Protocol header.
+ origin
+ The value of the 'Origin' header.
+ environ
+ The full WSGI environment for this request.
+
+ """
+
+ def __init__(self, sock, environ, version=76):
+ """
+ :param socket: The eventlet socket
+ :type socket: :class:`eventlet.greenio.GreenSocket`
+ :param environ: The wsgi environment
+ :param version: The WebSocket spec version to follow (default is 76)
+ """
+ self.log = environ.get('wsgi.errors', sys.stderr)
+ self.log_context = 'server={shost}/{spath} client={caddr}:{cport}'.format(
+ shost=environ.get('HTTP_HOST'),
+ spath=environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', ''),
+ caddr=environ.get('REMOTE_ADDR'), cport=environ.get('REMOTE_PORT'),
+ )
+ self.socket = sock
+ self.origin = environ.get('HTTP_ORIGIN')
+ self.protocol = environ.get('HTTP_WEBSOCKET_PROTOCOL')
+ self.path = environ.get('PATH_INFO')
+ self.environ = environ
+ self.version = version
+ self.websocket_closed = False
+ self._buf = b""
+ self._msgs = collections.deque()
+ self._sendlock = semaphore.Semaphore()
+
+ def _pack_message(self, message):
+ """Pack the message inside ``00`` and ``FF``
+
+ As per the dataframing section (5.3) for the websocket spec
+ """
+ if isinstance(message, six.text_type):
+ message = message.encode('utf-8')
+ elif not isinstance(message, six.binary_type):
+ message = six.b(str(message))
+ packed = b"\x00" + message + b"\xFF"
+ return packed
+
+ def _parse_messages(self):
+ """ Parses for messages in the buffer *buf*. It is assumed that
+ the buffer contains the start character for a message, but that it
+ may contain only part of the rest of the message.
+
+ Returns an array of messages, and the buffer remainder that
+ didn't contain any full messages."""
+ msgs = []
+ end_idx = 0
+ buf = self._buf
+ while buf:
+ frame_type = six.indexbytes(buf, 0)
+ if frame_type == 0:
+ # Normal message.
+ end_idx = buf.find(b"\xFF")
+ if end_idx == -1: # pragma NO COVER
+ break
+ msgs.append(buf[1:end_idx].decode('utf-8', 'replace'))
+ buf = buf[end_idx + 1:]
+ elif frame_type == 255:
+ # Closing handshake.
+ assert six.indexbytes(buf, 1) == 0, "Unexpected closing handshake: %r" % buf
+ self.websocket_closed = True
+ break
+ else:
+ raise ValueError("Don't understand how to parse this type of message: %r" % buf)
+ self._buf = buf
+ return msgs
+
+ def send(self, message):
+ """Send a message to the browser.
+
+ *message* should be convertable to a string; unicode objects should be
+ encodable as utf-8. Raises socket.error with errno of 32
+ (broken pipe) if the socket has already been closed by the client."""
+ packed = self._pack_message(message)
+ # if two greenthreads are trying to send at the same time
+ # on the same socket, sendlock prevents interleaving and corruption
+ self._sendlock.acquire()
+ try:
+ self.socket.sendall(packed)
+ finally:
+ self._sendlock.release()
+
+ def wait(self):
+ """Waits for and deserializes messages.
+
+ Returns a single message; the oldest not yet processed. If the client
+ has already closed the connection, returns None. This is different
+ from normal socket behavior because the empty string is a valid
+ websocket message."""
+ while not self._msgs:
+ # Websocket might be closed already.
+ if self.websocket_closed:
+ return None
+ # no parsed messages, must mean buf needs more data
+ delta = self.socket.recv(8096)
+ if delta == b'':
+ return None
+ self._buf += delta
+ msgs = self._parse_messages()
+ self._msgs.extend(msgs)
+ return self._msgs.popleft()
+
+ def _send_closing_frame(self, ignore_send_errors=False):
+ """Sends the closing frame to the client, if required."""
+ if self.version == 76 and not self.websocket_closed:
+ try:
+ self.socket.sendall(b"\xff\x00")
+ except SocketError:
+ # Sometimes, like when the remote side cuts off the connection,
+ # we don't care about this.
+ if not ignore_send_errors: # pragma NO COVER
+ raise
+ self.websocket_closed = True
+
+ def close(self):
+ """Forcibly close the websocket; generally it is preferable to
+ return from the handler method."""
+ try:
+ self._send_closing_frame(True)
+ self.socket.shutdown(True)
+ except SocketError as e:
+ if e.errno != errno.ENOTCONN:
+ self.log.write('{ctx} socket shutdown error: {e}'.format(ctx=self.log_context, e=e))
+ finally:
+ self.socket.close()
+
+
+class ConnectionClosedError(Exception):
+ pass
+
+
+class FailedConnectionError(Exception):
+ def __init__(self, status, message):
+ super(FailedConnectionError, self).__init__(status, message)
+ self.message = message
+ self.status = status
+
+
+class ProtocolError(ValueError):
+ pass
+
+
+class RFC6455WebSocket(WebSocket):
+ def __init__(self, sock, environ, version=13, protocol=None, client=False, extensions=None,
+ max_frame_length=DEFAULT_MAX_FRAME_LENGTH):
+ super(RFC6455WebSocket, self).__init__(sock, environ, version)
+ self.iterator = self._iter_frames()
+ self.client = client
+ self.protocol = protocol
+ self.extensions = extensions or {}
+
+ self._deflate_enc = None
+ self._deflate_dec = None
+ self.max_frame_length = max_frame_length
+ self._remote_close_data = None
+
+ class UTF8Decoder(object):
+ def __init__(self):
+ if utf8validator:
+ self.validator = utf8validator.Utf8Validator()
+ else:
+ self.validator = None
+ decoderclass = codecs.getincrementaldecoder('utf8')
+ self.decoder = decoderclass()
+
+ def reset(self):
+ if self.validator:
+ self.validator.reset()
+ self.decoder.reset()
+
+ def decode(self, data, final=False):
+ if self.validator:
+ valid, eocp, c_i, t_i = self.validator.validate(data)
+ if not valid:
+ raise ValueError('Data is not valid unicode')
+ return self.decoder.decode(data, final)
+
+ def _get_permessage_deflate_enc(self):
+ options = self.extensions.get("permessage-deflate")
+ if options is None:
+ return None
+
+ def _make():
+ return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
+ -options.get("client_max_window_bits" if self.client
+ else "server_max_window_bits",
+ zlib.MAX_WBITS))
+
+ if options.get("client_no_context_takeover" if self.client
+ else "server_no_context_takeover"):
+ # This option means we have to make a new one every time
+ return _make()
+ else:
+ if self._deflate_enc is None:
+ self._deflate_enc = _make()
+ return self._deflate_enc
+
+ def _get_permessage_deflate_dec(self, rsv1):
+ options = self.extensions.get("permessage-deflate")
+ if options is None or not rsv1:
+ return None
+
+ def _make():
+ return zlib.decompressobj(-options.get("server_max_window_bits" if self.client
+ else "client_max_window_bits",
+ zlib.MAX_WBITS))
+
+ if options.get("server_no_context_takeover" if self.client
+ else "client_no_context_takeover"):
+ # This option means we have to make a new one every time
+ return _make()
+ else:
+ if self._deflate_dec is None:
+ self._deflate_dec = _make()
+ return self._deflate_dec
+
+ def _get_bytes(self, numbytes):
+ data = b''
+ while len(data) < numbytes:
+ d = self.socket.recv(numbytes - len(data))
+ if not d:
+ raise ConnectionClosedError()
+ data = data + d
+ return data
+
+ class Message(object):
+ def __init__(self, opcode, max_frame_length, decoder=None, decompressor=None):
+ self.decoder = decoder
+ self.data = []
+ self.finished = False
+ self.opcode = opcode
+ self.decompressor = decompressor
+ self.max_frame_length = max_frame_length
+
+ def push(self, data, final=False):
+ self.finished = final
+ self.data.append(data)
+
+ def getvalue(self):
+ data = b"".join(self.data)
+ if not self.opcode & 8 and self.decompressor:
+ data = self.decompressor.decompress(data + b"\x00\x00\xff\xff", self.max_frame_length)
+ if self.decompressor.unconsumed_tail:
+ raise FailedConnectionError(
+ 1009,
+ "Incoming compressed frame exceeds length limit of {} bytes.".format(self.max_frame_length))
+
+ if self.decoder:
+ data = self.decoder.decode(data, self.finished)
+ return data
+
+ @staticmethod
+ def _apply_mask(data, mask, length=None, offset=0):
+ if length is None:
+ length = len(data)
+ cnt = range(length)
+ return b''.join(six.int2byte(six.indexbytes(data, i) ^ mask[(offset + i) % 4]) for i in cnt)
+
+ def _handle_control_frame(self, opcode, data):
+ if opcode == 8: # connection close
+ self._remote_close_data = data
+ if not data:
+ status = 1000
+ elif len(data) > 1:
+ status = struct.unpack_from('!H', data)[0]
+ if not status or status not in VALID_CLOSE_STATUS:
+ raise FailedConnectionError(
+ 1002,
+ "Unexpected close status code.")
+ try:
+ data = self.UTF8Decoder().decode(data[2:], True)
+ except (UnicodeDecodeError, ValueError):
+ raise FailedConnectionError(
+ 1002,
+ "Close message data should be valid UTF-8.")
+ else:
+ status = 1002
+ self.close(close_data=(status, ''))
+ raise ConnectionClosedError()
+ elif opcode == 9: # ping
+ self.send(data, control_code=0xA)
+ elif opcode == 0xA: # pong
+ pass
+ else:
+ raise FailedConnectionError(
+ 1002, "Unknown control frame received.")
+
+ def _iter_frames(self):
+ fragmented_message = None
+ try:
+ while True:
+ message = self._recv_frame(message=fragmented_message)
+ if message.opcode & 8:
+ self._handle_control_frame(
+ message.opcode, message.getvalue())
+ continue
+ if fragmented_message and message is not fragmented_message:
+ raise RuntimeError('Unexpected message change.')
+ fragmented_message = message
+ if message.finished:
+ data = fragmented_message.getvalue()
+ fragmented_message = None
+ yield data
+ except FailedConnectionError:
+ exc_typ, exc_val, exc_tb = sys.exc_info()
+ self.close(close_data=(exc_val.status, exc_val.message))
+ except ConnectionClosedError:
+ return
+ except Exception:
+ self.close(close_data=(1011, 'Internal Server Error'))
+ raise
+
+ def _recv_frame(self, message=None):
+ recv = self._get_bytes
+
+ # Unpacking the frame described in Section 5.2 of RFC6455
+ # (https://tools.ietf.org/html/rfc6455#section-5.2)
+ header = recv(2)
+ a, b = struct.unpack('!BB', header)
+ finished = a >> 7 == 1
+ rsv123 = a >> 4 & 7
+ rsv1 = rsv123 & 4
+ if rsv123:
+ if rsv1 and "permessage-deflate" not in self.extensions:
+ # must be zero - unless it's compressed then rsv1 is true
+ raise FailedConnectionError(
+ 1002,
+ "RSV1, RSV2, RSV3: MUST be 0 unless an extension is"
+ " negotiated that defines meanings for non-zero values.")
+ opcode = a & 15
+ if opcode not in (0, 1, 2, 8, 9, 0xA):
+ raise FailedConnectionError(1002, "Unknown opcode received.")
+ masked = b & 128 == 128
+ if not masked and not self.client:
+ raise FailedConnectionError(1002, "A client MUST mask all frames"
+ " that it sends to the server")
+ length = b & 127
+ if opcode & 8:
+ if not finished:
+ raise FailedConnectionError(1002, "Control frames must not"
+ " be fragmented.")
+ if length > 125:
+ raise FailedConnectionError(
+ 1002,
+ "All control frames MUST have a payload length of 125"
+ " bytes or less")
+ elif opcode and message:
+ raise FailedConnectionError(
+ 1002,
+ "Received a non-continuation opcode within"
+ " fragmented message.")
+ elif not opcode and not message:
+ raise FailedConnectionError(
+ 1002,
+ "Received continuation opcode with no previous"
+ " fragments received.")
+ if length == 126:
+ length = struct.unpack('!H', recv(2))[0]
+ elif length == 127:
+ length = struct.unpack('!Q', recv(8))[0]
+
+ if length > self.max_frame_length:
+ raise FailedConnectionError(1009, "Incoming frame of {} bytes is above length limit of {} bytes.".format(
+ length, self.max_frame_length))
+ if masked:
+ mask = struct.unpack('!BBBB', recv(4))
+ received = 0
+ if not message or opcode & 8:
+ decoder = self.UTF8Decoder() if opcode == 1 else None
+ decompressor = self._get_permessage_deflate_dec(rsv1)
+ message = self.Message(opcode, self.max_frame_length, decoder=decoder, decompressor=decompressor)
+ if not length:
+ message.push(b'', final=finished)
+ else:
+ while received < length:
+ d = self.socket.recv(length - received)
+ if not d:
+ raise ConnectionClosedError()
+ dlen = len(d)
+ if masked:
+ d = self._apply_mask(d, mask, length=dlen, offset=received)
+ received = received + dlen
+ try:
+ message.push(d, final=finished)
+ except (UnicodeDecodeError, ValueError):
+ raise FailedConnectionError(
+ 1007, "Text data must be valid utf-8")
+ return message
+
+ def _pack_message(self, message, masked=False,
+ continuation=False, final=True, control_code=None):
+ is_text = False
+ if isinstance(message, six.text_type):
+ message = message.encode('utf-8')
+ is_text = True
+
+ compress_bit = 0
+ compressor = self._get_permessage_deflate_enc()
+ # Control frames are identified by opcodes where the most significant
+ # bit of the opcode is 1. Currently defined opcodes for control frames
+ # include 0x8 (Close), 0x9 (Ping), and 0xA (Pong). Opcodes 0xB-0xF are
+ # reserved for further control frames yet to be defined.
+ # https://datatracker.ietf.org/doc/html/rfc6455#section-5.5
+ is_control_frame = (control_code or 0) & 8
+ # An endpoint MUST NOT set the "Per-Message Compressed" bit of control
+ # frames and non-first fragments of a data message. An endpoint
+ # receiving such a frame MUST _Fail the WebSocket Connection_.
+ # https://datatracker.ietf.org/doc/html/rfc7692#section-6.1
+ if message and compressor and not is_control_frame:
+ message = compressor.compress(message)
+ message += compressor.flush(zlib.Z_SYNC_FLUSH)
+ assert message[-4:] == b"\x00\x00\xff\xff"
+ message = message[:-4]
+ compress_bit = 1 << 6
+
+ length = len(message)
+ if not length:
+ # no point masking empty data
+ masked = False
+ if control_code:
+ if control_code not in (8, 9, 0xA):
+ raise ProtocolError('Unknown control opcode.')
+ if continuation or not final:
+ raise ProtocolError('Control frame cannot be a fragment.')
+ if length > 125:
+ raise ProtocolError('Control frame data too large (>125).')
+ header = struct.pack('!B', control_code | 1 << 7)
+ else:
+ opcode = 0 if continuation else ((1 if is_text else 2) | compress_bit)
+ header = struct.pack('!B', opcode | (1 << 7 if final else 0))
+ lengthdata = 1 << 7 if masked else 0
+ if length > 65535:
+ lengthdata = struct.pack('!BQ', lengthdata | 127, length)
+ elif length > 125:
+ lengthdata = struct.pack('!BH', lengthdata | 126, length)
+ else:
+ lengthdata = struct.pack('!B', lengthdata | length)
+ if masked:
+ # NOTE: RFC6455 states:
+ # A server MUST NOT mask any frames that it sends to the client
+ rand = Random(time.time())
+ mask = [rand.getrandbits(8) for _ in six.moves.xrange(4)]
+ message = RFC6455WebSocket._apply_mask(message, mask, length)
+ maskdata = struct.pack('!BBBB', *mask)
+ else:
+ maskdata = b''
+
+ return b''.join((header, lengthdata, maskdata, message))
+
+ def wait(self):
+ for i in self.iterator:
+ return i
+
+ def _send(self, frame):
+ self._sendlock.acquire()
+ try:
+ self.socket.sendall(frame)
+ finally:
+ self._sendlock.release()
+
+ def send(self, message, **kw):
+ kw['masked'] = self.client
+ payload = self._pack_message(message, **kw)
+ self._send(payload)
+
+ def _send_closing_frame(self, ignore_send_errors=False, close_data=None):
+ if self.version in (8, 13) and not self.websocket_closed:
+ if close_data is not None:
+ status, msg = close_data
+ if isinstance(msg, six.text_type):
+ msg = msg.encode('utf-8')
+ data = struct.pack('!H', status) + msg
+ else:
+ data = ''
+ try:
+ self.send(data, control_code=8)
+ except SocketError:
+ # Sometimes, like when the remote side cuts off the connection,
+ # we don't care about this.
+ if not ignore_send_errors: # pragma NO COVER
+ raise
+ self.websocket_closed = True
+
+ def close(self, close_data=None):
+ """Forcibly close the websocket; generally it is preferable to
+ return from the handler method."""
+ try:
+ self._send_closing_frame(close_data=close_data, ignore_send_errors=True)
+ self.socket.shutdown(socket.SHUT_WR)
+ except SocketError as e:
+ if e.errno != errno.ENOTCONN:
+ self.log.write('{ctx} socket shutdown error: {e}'.format(ctx=self.log_context, e=e))
+ finally:
+ self.socket.close()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/wsgi.py b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/wsgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2c8d2809f304a9abab5cd48962a93174dbac664
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/eventlet/wsgi.py
@@ -0,0 +1,1041 @@
+import errno
+import os
+import sys
+import time
+import traceback
+import types
+import warnings
+
+import eventlet
+from eventlet import greenio
+from eventlet import support
+from eventlet.corolocal import local
+from eventlet.green import BaseHTTPServer
+from eventlet.green import socket
+import six
+from six.moves import urllib
+
+
+DEFAULT_MAX_SIMULTANEOUS_REQUESTS = 1024
+DEFAULT_MAX_HTTP_VERSION = 'HTTP/1.1'
+MAX_REQUEST_LINE = 8192
+MAX_HEADER_LINE = 8192
+MAX_TOTAL_HEADER_SIZE = 65536
+MINIMUM_CHUNK_SIZE = 4096
+# %(client_port)s is also available
+DEFAULT_LOG_FORMAT = ('%(client_ip)s - - [%(date_time)s] "%(request_line)s"'
+ ' %(status_code)s %(body_length)s %(wall_seconds).6f')
+RESPONSE_414 = b'''HTTP/1.0 414 Request URI Too Long\r\n\
+Connection: close\r\n\
+Content-Length: 0\r\n\r\n'''
+is_accepting = True
+
+STATE_IDLE = 'idle'
+STATE_REQUEST = 'request'
+STATE_CLOSE = 'close'
+
+__all__ = ['server', 'format_date_time']
+
+# Weekday and month names for HTTP date/time formatting; always English!
+_weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
+_monthname = [None, # Dummy so we can use 1-based month numbers
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
+
+
+def format_date_time(timestamp):
+ """Formats a unix timestamp into an HTTP standard string."""
+ year, month, day, hh, mm, ss, wd, _y, _z = time.gmtime(timestamp)
+ return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
+ _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
+ )
+
+
+def addr_to_host_port(addr):
+ host = 'unix'
+ port = ''
+ if isinstance(addr, tuple):
+ host = addr[0]
+ port = addr[1]
+ return (host, port)
+
+
+# Collections of error codes to compare against. Not all attributes are set
+# on errno module on all platforms, so some are literals :(
+BAD_SOCK = set((errno.EBADF, 10053))
+BROKEN_SOCK = set((errno.EPIPE, errno.ECONNRESET))
+
+
+class ChunkReadError(ValueError):
+ pass
+
+
+WSGI_LOCAL = local()
+
+
+class Input(object):
+
+ def __init__(self,
+ rfile,
+ content_length,
+ sock,
+ wfile=None,
+ wfile_line=None,
+ chunked_input=False):
+
+ self.rfile = rfile
+ self._sock = sock
+ if content_length is not None:
+ content_length = int(content_length)
+ self.content_length = content_length
+
+ self.wfile = wfile
+ self.wfile_line = wfile_line
+
+ self.position = 0
+ self.chunked_input = chunked_input
+ self.chunk_length = -1
+
+ # (optional) headers to send with a "100 Continue" response. Set by
+ # calling set_hundred_continue_respose_headers() on env['wsgi.input']
+ self.hundred_continue_headers = None
+ self.is_hundred_continue_response_sent = False
+
+ # handle_one_response should give us a ref to the response state so we
+ # know whether we can still send the 100 Continue; until then, though,
+ # we're flying blind
+ self.headers_sent = None
+
+ def send_hundred_continue_response(self):
+ if self.headers_sent:
+ # To late; application has already started sending data back
+ # to the client
+ # TODO: maybe log a warning if self.hundred_continue_headers
+ # is not None?
+ return
+
+ towrite = []
+
+ # 100 Continue status line
+ towrite.append(self.wfile_line)
+
+ # Optional headers
+ if self.hundred_continue_headers is not None:
+ # 100 Continue headers
+ for header in self.hundred_continue_headers:
+ towrite.append(six.b('%s: %s\r\n' % header))
+
+ # Blank line
+ towrite.append(b'\r\n')
+
+ self.wfile.writelines(towrite)
+ self.wfile.flush()
+
+ # Reinitialize chunk_length (expect more data)
+ self.chunk_length = -1
+
+ @property
+ def should_send_hundred_continue(self):
+ return self.wfile is not None and not self.is_hundred_continue_response_sent
+
+ def _do_read(self, reader, length=None):
+ if self.should_send_hundred_continue:
+ # 100 Continue response
+ self.send_hundred_continue_response()
+ self.is_hundred_continue_response_sent = True
+ if (self.content_length is not None) and (
+ length is None or length > self.content_length - self.position):
+ length = self.content_length - self.position
+ if not length:
+ return b''
+ try:
+ read = reader(length)
+ except greenio.SSL.ZeroReturnError:
+ read = b''
+ self.position += len(read)
+ return read
+
+ def _chunked_read(self, rfile, length=None, use_readline=False):
+ if self.should_send_hundred_continue:
+ # 100 Continue response
+ self.send_hundred_continue_response()
+ self.is_hundred_continue_response_sent = True
+ try:
+ if length == 0:
+ return b""
+
+ if length and length < 0:
+ length = None
+
+ if use_readline:
+ reader = self.rfile.readline
+ else:
+ reader = self.rfile.read
+
+ response = []
+ while self.chunk_length != 0:
+ maxreadlen = self.chunk_length - self.position
+ if length is not None and length < maxreadlen:
+ maxreadlen = length
+
+ if maxreadlen > 0:
+ data = reader(maxreadlen)
+ if not data:
+ self.chunk_length = 0
+ raise IOError("unexpected end of file while parsing chunked data")
+
+ datalen = len(data)
+ response.append(data)
+
+ self.position += datalen
+ if self.chunk_length == self.position:
+ rfile.readline()
+
+ if length is not None:
+ length -= datalen
+ if length == 0:
+ break
+ if use_readline and data[-1:] == b"\n":
+ break
+ else:
+ try:
+ self.chunk_length = int(rfile.readline().split(b";", 1)[0], 16)
+ except ValueError as err:
+ raise ChunkReadError(err)
+ self.position = 0
+ if self.chunk_length == 0:
+ rfile.readline()
+ except greenio.SSL.ZeroReturnError:
+ pass
+ return b''.join(response)
+
+ def read(self, length=None):
+ if self.chunked_input:
+ return self._chunked_read(self.rfile, length)
+ return self._do_read(self.rfile.read, length)
+
+ def readline(self, size=None):
+ if self.chunked_input:
+ return self._chunked_read(self.rfile, size, True)
+ else:
+ return self._do_read(self.rfile.readline, size)
+
+ def readlines(self, hint=None):
+ if self.chunked_input:
+ lines = []
+ for line in iter(self.readline, b''):
+ lines.append(line)
+ if hint and hint > 0:
+ hint -= len(line)
+ if hint <= 0:
+ break
+ return lines
+ else:
+ return self._do_read(self.rfile.readlines, hint)
+
+ def __iter__(self):
+ return iter(self.read, b'')
+
+ def get_socket(self):
+ return self._sock
+
+ def set_hundred_continue_response_headers(self, headers,
+ capitalize_response_headers=True):
+ # Response headers capitalization (default)
+ # CONTent-TYpe: TExt/PlaiN -> Content-Type: TExt/PlaiN
+ # Per HTTP RFC standard, header name is case-insensitive.
+ # Please, fix your client to ignore header case if possible.
+ if capitalize_response_headers:
+ headers = [
+ ('-'.join([x.capitalize() for x in key.split('-')]), value)
+ for key, value in headers]
+ self.hundred_continue_headers = headers
+
+ def discard(self, buffer_size=16 << 10):
+ while self.read(buffer_size):
+ pass
+
+
+class HeaderLineTooLong(Exception):
+ pass
+
+
+class HeadersTooLarge(Exception):
+ pass
+
+
+def get_logger(log, debug):
+ if callable(getattr(log, 'info', None)) \
+ and callable(getattr(log, 'debug', None)):
+ return log
+ else:
+ return LoggerFileWrapper(log or sys.stderr, debug)
+
+
+class LoggerNull(object):
+ def __init__(self):
+ pass
+
+ def error(self, msg, *args, **kwargs):
+ pass
+
+ def info(self, msg, *args, **kwargs):
+ pass
+
+ def debug(self, msg, *args, **kwargs):
+ pass
+
+ def write(self, msg, *args):
+ pass
+
+
+class LoggerFileWrapper(LoggerNull):
+ def __init__(self, log, debug):
+ self.log = log
+ self._debug = debug
+
+ def error(self, msg, *args, **kwargs):
+ self.write(msg, *args)
+
+ def info(self, msg, *args, **kwargs):
+ self.write(msg, *args)
+
+ def debug(self, msg, *args, **kwargs):
+ if self._debug:
+ self.write(msg, *args)
+
+ def write(self, msg, *args):
+ msg = msg + '\n'
+ if args:
+ msg = msg % args
+ self.log.write(msg)
+
+
+class FileObjectForHeaders(object):
+
+ def __init__(self, fp):
+ self.fp = fp
+ self.total_header_size = 0
+
+ def readline(self, size=-1):
+ sz = size
+ if size < 0:
+ sz = MAX_HEADER_LINE
+ rv = self.fp.readline(sz)
+ if len(rv) >= MAX_HEADER_LINE:
+ raise HeaderLineTooLong()
+ self.total_header_size += len(rv)
+ if self.total_header_size > MAX_TOTAL_HEADER_SIZE:
+ raise HeadersTooLarge()
+ return rv
+
+
+class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
+ protocol_version = 'HTTP/1.1'
+ minimum_chunk_size = MINIMUM_CHUNK_SIZE
+ capitalize_response_headers = True
+
+ # https://github.com/eventlet/eventlet/issues/295
+ # Stdlib default is 0 (unbuffered), but then `wfile.writelines()` looses data
+ # so before going back to unbuffered, remove any usage of `writelines`.
+ wbufsize = 16 << 10
+
+ def __init__(self, conn_state, server):
+ self.request = conn_state[1]
+ self.client_address = conn_state[0]
+ self.conn_state = conn_state
+ self.server = server
+ self.setup()
+ try:
+ self.handle()
+ finally:
+ self.finish()
+
+ def setup(self):
+ # overriding SocketServer.setup to correctly handle SSL.Connection objects
+ conn = self.connection = self.request
+
+ # TCP_QUICKACK is a better alternative to disabling Nagle's algorithm
+ # https://news.ycombinator.com/item?id=10607422
+ if getattr(socket, 'TCP_QUICKACK', None):
+ try:
+ conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, True)
+ except socket.error:
+ pass
+
+ try:
+ self.rfile = conn.makefile('rb', self.rbufsize)
+ self.wfile = conn.makefile('wb', self.wbufsize)
+ except (AttributeError, NotImplementedError):
+ if hasattr(conn, 'send') and hasattr(conn, 'recv'):
+ # it's an SSL.Connection
+ self.rfile = socket._fileobject(conn, "rb", self.rbufsize)
+ self.wfile = socket._fileobject(conn, "wb", self.wbufsize)
+ else:
+ # it's a SSLObject, or a martian
+ raise NotImplementedError(
+ '''eventlet.wsgi doesn't support sockets of type {0}'''.format(type(conn)))
+
+ def handle(self):
+ self.close_connection = True
+
+ while True:
+ self.handle_one_request()
+ if self.conn_state[2] == STATE_CLOSE:
+ self.close_connection = 1
+ if self.close_connection:
+ break
+
+ def _read_request_line(self):
+ if self.rfile.closed:
+ self.close_connection = 1
+ return ''
+
+ try:
+ sock = self.rfile._sock if six.PY2 else self.connection
+ if self.server.keepalive and not isinstance(self.server.keepalive, bool):
+ sock.settimeout(self.server.keepalive)
+ line = self.rfile.readline(self.server.url_length_limit)
+ sock.settimeout(self.server.socket_timeout)
+ return line
+ except greenio.SSL.ZeroReturnError:
+ pass
+ except socket.error as e:
+ last_errno = support.get_errno(e)
+ if last_errno in BROKEN_SOCK:
+ self.server.log.debug('({0}) connection reset by peer {1!r}'.format(
+ self.server.pid,
+ self.client_address))
+ elif last_errno not in BAD_SOCK:
+ raise
+ return ''
+
+ def handle_one_request(self):
+ if self.server.max_http_version:
+ self.protocol_version = self.server.max_http_version
+
+ self.raw_requestline = self._read_request_line()
+ if not self.raw_requestline:
+ self.close_connection = 1
+ return
+ if len(self.raw_requestline) >= self.server.url_length_limit:
+ self.wfile.write(RESPONSE_414)
+ self.close_connection = 1
+ return
+
+ orig_rfile = self.rfile
+ try:
+ self.rfile = FileObjectForHeaders(self.rfile)
+ if not self.parse_request():
+ return
+ except HeaderLineTooLong:
+ self.wfile.write(
+ b"HTTP/1.0 400 Header Line Too Long\r\n"
+ b"Connection: close\r\nContent-length: 0\r\n\r\n")
+ self.close_connection = 1
+ return
+ except HeadersTooLarge:
+ self.wfile.write(
+ b"HTTP/1.0 400 Headers Too Large\r\n"
+ b"Connection: close\r\nContent-length: 0\r\n\r\n")
+ self.close_connection = 1
+ return
+ finally:
+ self.rfile = orig_rfile
+
+ content_length = self.headers.get('content-length')
+ if content_length is not None:
+ try:
+ if int(content_length) < 0:
+ raise ValueError
+ except ValueError:
+ # Negative, or not an int at all
+ self.wfile.write(
+ b"HTTP/1.0 400 Bad Request\r\n"
+ b"Connection: close\r\nContent-length: 0\r\n\r\n")
+ self.close_connection = 1
+ return
+
+ self.environ = self.get_environ()
+ self.application = self.server.app
+ try:
+ self.server.outstanding_requests += 1
+ try:
+ self.handle_one_response()
+ except socket.error as e:
+ # Broken pipe, connection reset by peer
+ if support.get_errno(e) not in BROKEN_SOCK:
+ raise
+ finally:
+ self.server.outstanding_requests -= 1
+
+ def handle_one_response(self):
+ start = time.time()
+ headers_set = []
+ headers_sent = []
+ # Grab the request input now; app may try to replace it in the environ
+ request_input = self.environ['eventlet.input']
+ # Push the headers-sent state into the Input so it won't send a
+ # 100 Continue response if we've already started a response.
+ request_input.headers_sent = headers_sent
+
+ wfile = self.wfile
+ result = None
+ use_chunked = [False]
+ length = [0]
+ status_code = [200]
+
+ def write(data):
+ towrite = []
+ if not headers_set:
+ raise AssertionError("write() before start_response()")
+ elif not headers_sent:
+ status, response_headers = headers_set
+ headers_sent.append(1)
+ header_list = [header[0].lower() for header in response_headers]
+ towrite.append(six.b('%s %s\r\n' % (self.protocol_version, status)))
+ for header in response_headers:
+ towrite.append(six.b('%s: %s\r\n' % header))
+
+ # send Date header?
+ if 'date' not in header_list:
+ towrite.append(six.b('Date: %s\r\n' % (format_date_time(time.time()),)))
+
+ client_conn = self.headers.get('Connection', '').lower()
+ send_keep_alive = False
+ if self.close_connection == 0 and \
+ self.server.keepalive and (client_conn == 'keep-alive' or
+ (self.request_version == 'HTTP/1.1' and
+ not client_conn == 'close')):
+ # only send keep-alives back to clients that sent them,
+ # it's redundant for 1.1 connections
+ send_keep_alive = (client_conn == 'keep-alive')
+ self.close_connection = 0
+ else:
+ self.close_connection = 1
+
+ if 'content-length' not in header_list:
+ if self.request_version == 'HTTP/1.1':
+ use_chunked[0] = True
+ towrite.append(b'Transfer-Encoding: chunked\r\n')
+ elif 'content-length' not in header_list:
+ # client is 1.0 and therefore must read to EOF
+ self.close_connection = 1
+
+ if self.close_connection:
+ towrite.append(b'Connection: close\r\n')
+ elif send_keep_alive:
+ towrite.append(b'Connection: keep-alive\r\n')
+ # Spec says timeout must be an integer, but we allow sub-second
+ int_timeout = int(self.server.keepalive or 0)
+ if not isinstance(self.server.keepalive, bool) and int_timeout:
+ towrite.append(b'Keep-Alive: timeout=%d\r\n' % int_timeout)
+ towrite.append(b'\r\n')
+ # end of header writing
+
+ if use_chunked[0]:
+ # Write the chunked encoding
+ towrite.append(six.b("%x" % (len(data),)) + b"\r\n" + data + b"\r\n")
+ else:
+ towrite.append(data)
+ wfile.writelines(towrite)
+ wfile.flush()
+ length[0] = length[0] + sum(map(len, towrite))
+
+ def start_response(status, response_headers, exc_info=None):
+ status_code[0] = status.split()[0]
+ if exc_info:
+ try:
+ if headers_sent:
+ # Re-raise original exception if headers sent
+ six.reraise(exc_info[0], exc_info[1], exc_info[2])
+ finally:
+ # Avoid dangling circular ref
+ exc_info = None
+
+ # Response headers capitalization
+ # CONTent-TYpe: TExt/PlaiN -> Content-Type: TExt/PlaiN
+ # Per HTTP RFC standard, header name is case-insensitive.
+ # Please, fix your client to ignore header case if possible.
+ if self.capitalize_response_headers:
+ if six.PY2:
+ def cap(x):
+ return x.capitalize()
+ else:
+ def cap(x):
+ return x.encode('latin1').capitalize().decode('latin1')
+
+ response_headers = [
+ ('-'.join([cap(x) for x in key.split('-')]), value)
+ for key, value in response_headers]
+
+ headers_set[:] = [status, response_headers]
+ return write
+
+ try:
+ try:
+ WSGI_LOCAL.already_handled = False
+ result = self.application(self.environ, start_response)
+
+ # Set content-length if possible
+ if headers_set and not headers_sent and hasattr(result, '__len__'):
+ # We've got a complete final response
+ if 'Content-Length' not in [h for h, _v in headers_set[1]]:
+ headers_set[1].append(('Content-Length', str(sum(map(len, result)))))
+ if request_input.should_send_hundred_continue:
+ # We've got a complete final response, and never sent a 100 Continue.
+ # There's no chance we'll need to read the body as we stream out the
+ # response, so we can be nice and send a Connection: close header.
+ self.close_connection = 1
+
+ towrite = []
+ towrite_size = 0
+ just_written_size = 0
+ minimum_write_chunk_size = int(self.environ.get(
+ 'eventlet.minimum_write_chunk_size', self.minimum_chunk_size))
+ for data in result:
+ if len(data) == 0:
+ continue
+ if isinstance(data, six.text_type):
+ data = data.encode('ascii')
+
+ towrite.append(data)
+ towrite_size += len(data)
+ if towrite_size >= minimum_write_chunk_size:
+ write(b''.join(towrite))
+ towrite = []
+ just_written_size = towrite_size
+ towrite_size = 0
+ if WSGI_LOCAL.already_handled:
+ self.close_connection = 1
+ return
+ if towrite:
+ just_written_size = towrite_size
+ write(b''.join(towrite))
+ if not headers_sent or (use_chunked[0] and just_written_size):
+ write(b'')
+ except Exception:
+ self.close_connection = 1
+ tb = traceback.format_exc()
+ self.server.log.info(tb)
+ if not headers_sent:
+ err_body = six.b(tb) if self.server.debug else b''
+ start_response("500 Internal Server Error",
+ [('Content-type', 'text/plain'),
+ ('Content-length', len(err_body))])
+ write(err_body)
+ finally:
+ if hasattr(result, 'close'):
+ result.close()
+ if request_input.should_send_hundred_continue:
+ # We just sent the final response, no 100 Continue. Client may or
+ # may not have started to send a body, and if we keep the connection
+ # open we've seen clients either
+ # * send a body, then start a new request
+ # * skip the body and go straight to a new request
+ # Looks like the most broadly compatible option is to close the
+ # connection and let the client retry.
+ # https://curl.se/mail/lib-2004-08/0002.html
+ # Note that we likely *won't* send a Connection: close header at this point
+ self.close_connection = 1
+
+ if (request_input.chunked_input or
+ request_input.position < (request_input.content_length or 0)):
+ # Read and discard body if connection is going to be reused
+ if self.close_connection == 0:
+ try:
+ request_input.discard()
+ except ChunkReadError as e:
+ self.close_connection = 1
+ self.server.log.error((
+ 'chunked encoding error while discarding request body.'
+ + ' client={0} request="{1}" error="{2}"').format(
+ self.get_client_address()[0], self.requestline, e,
+ ))
+ except IOError as e:
+ self.close_connection = 1
+ self.server.log.error((
+ 'I/O error while discarding request body.'
+ + ' client={0} request="{1}" error="{2}"').format(
+ self.get_client_address()[0], self.requestline, e,
+ ))
+ finish = time.time()
+
+ for hook, args, kwargs in self.environ['eventlet.posthooks']:
+ hook(self.environ, *args, **kwargs)
+
+ if self.server.log_output:
+ client_host, client_port = self.get_client_address()
+
+ self.server.log.info(self.server.log_format % {
+ 'client_ip': client_host,
+ 'client_port': client_port,
+ 'date_time': self.log_date_time_string(),
+ 'request_line': self.requestline,
+ 'status_code': status_code[0],
+ 'body_length': length[0],
+ 'wall_seconds': finish - start,
+ })
+
+ def get_client_address(self):
+ host, port = addr_to_host_port(self.client_address)
+
+ if self.server.log_x_forwarded_for:
+ forward = self.headers.get('X-Forwarded-For', '').replace(' ', '')
+ if forward:
+ host = forward + ',' + host
+ return (host, port)
+
+ def get_environ(self):
+ env = self.server.get_environ()
+ env['REQUEST_METHOD'] = self.command
+ env['SCRIPT_NAME'] = ''
+
+ pq = self.path.split('?', 1)
+ env['RAW_PATH_INFO'] = pq[0]
+ if six.PY2:
+ env['PATH_INFO'] = urllib.parse.unquote(pq[0])
+ else:
+ env['PATH_INFO'] = urllib.parse.unquote(pq[0], encoding='latin1')
+ if len(pq) > 1:
+ env['QUERY_STRING'] = pq[1]
+
+ ct = self.headers.get('content-type')
+ if ct is None:
+ try:
+ ct = self.headers.type
+ except AttributeError:
+ ct = self.headers.get_content_type()
+ env['CONTENT_TYPE'] = ct
+
+ length = self.headers.get('content-length')
+ if length:
+ env['CONTENT_LENGTH'] = length
+ env['SERVER_PROTOCOL'] = 'HTTP/1.0'
+
+ sockname = self.request.getsockname()
+ server_addr = addr_to_host_port(sockname)
+ env['SERVER_NAME'] = server_addr[0]
+ env['SERVER_PORT'] = str(server_addr[1])
+ client_addr = addr_to_host_port(self.client_address)
+ env['REMOTE_ADDR'] = client_addr[0]
+ env['REMOTE_PORT'] = str(client_addr[1])
+ env['GATEWAY_INTERFACE'] = 'CGI/1.1'
+
+ try:
+ headers = self.headers.headers
+ except AttributeError:
+ headers = self.headers._headers
+ else:
+ headers = [h.split(':', 1) for h in headers]
+
+ env['headers_raw'] = headers_raw = tuple((k, v.strip(' \t\n\r')) for k, v in headers)
+ for k, v in headers_raw:
+ k = k.replace('-', '_').upper()
+ if k in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
+ # These do not get the HTTP_ prefix and were handled above
+ continue
+ envk = 'HTTP_' + k
+ if envk in env:
+ env[envk] += ',' + v
+ else:
+ env[envk] = v
+
+ if env.get('HTTP_EXPECT', '').lower() == '100-continue':
+ wfile = self.wfile
+ wfile_line = b'HTTP/1.1 100 Continue\r\n'
+ else:
+ wfile = None
+ wfile_line = None
+ chunked = env.get('HTTP_TRANSFER_ENCODING', '').lower() == 'chunked'
+ env['wsgi.input'] = env['eventlet.input'] = Input(
+ self.rfile, length, self.connection, wfile=wfile, wfile_line=wfile_line,
+ chunked_input=chunked)
+ env['eventlet.posthooks'] = []
+
+ return env
+
+ def finish(self):
+ try:
+ BaseHTTPServer.BaseHTTPRequestHandler.finish(self)
+ except socket.error as e:
+ # Broken pipe, connection reset by peer
+ if support.get_errno(e) not in BROKEN_SOCK:
+ raise
+ greenio.shutdown_safe(self.connection)
+ self.connection.close()
+
+ def handle_expect_100(self):
+ return True
+
+
+class Server(BaseHTTPServer.HTTPServer):
+
+ def __init__(self,
+ socket,
+ address,
+ app,
+ log=None,
+ environ=None,
+ max_http_version=None,
+ protocol=HttpProtocol,
+ minimum_chunk_size=None,
+ log_x_forwarded_for=True,
+ keepalive=True,
+ log_output=True,
+ log_format=DEFAULT_LOG_FORMAT,
+ url_length_limit=MAX_REQUEST_LINE,
+ debug=True,
+ socket_timeout=None,
+ capitalize_response_headers=True):
+
+ self.outstanding_requests = 0
+ self.socket = socket
+ self.address = address
+ self.log = LoggerNull()
+ if log_output:
+ self.log = get_logger(log, debug)
+ self.app = app
+ self.keepalive = keepalive
+ self.environ = environ
+ self.max_http_version = max_http_version
+ self.protocol = protocol
+ self.pid = os.getpid()
+ self.minimum_chunk_size = minimum_chunk_size
+ self.log_x_forwarded_for = log_x_forwarded_for
+ self.log_output = log_output
+ self.log_format = log_format
+ self.url_length_limit = url_length_limit
+ self.debug = debug
+ self.socket_timeout = socket_timeout
+ self.capitalize_response_headers = capitalize_response_headers
+
+ if not self.capitalize_response_headers:
+ warnings.warn("""capitalize_response_headers is disabled.
+ Please, make sure you know what you are doing.
+ HTTP headers names are case-insensitive per RFC standard.
+ Most likely, you need to fix HTTP parsing in your client software.""",
+ DeprecationWarning, stacklevel=3)
+
+ def get_environ(self):
+ d = {
+ 'wsgi.errors': sys.stderr,
+ 'wsgi.version': (1, 0),
+ 'wsgi.multithread': True,
+ 'wsgi.multiprocess': False,
+ 'wsgi.run_once': False,
+ 'wsgi.url_scheme': 'http',
+ }
+ # detect secure socket
+ if hasattr(self.socket, 'do_handshake'):
+ d['wsgi.url_scheme'] = 'https'
+ d['HTTPS'] = 'on'
+ if self.environ is not None:
+ d.update(self.environ)
+ return d
+
+ def process_request(self, conn_state):
+ # The actual request handling takes place in __init__, so we need to
+ # set minimum_chunk_size before __init__ executes and we don't want to modify
+ # class variable
+ proto = new(self.protocol)
+ if self.minimum_chunk_size is not None:
+ proto.minimum_chunk_size = self.minimum_chunk_size
+ proto.capitalize_response_headers = self.capitalize_response_headers
+ try:
+ proto.__init__(conn_state, self)
+ except socket.timeout:
+ # Expected exceptions are not exceptional
+ conn_state[1].close()
+ # similar to logging "accepted" in server()
+ self.log.debug('({0}) timed out {1!r}'.format(self.pid, conn_state[0]))
+
+ def log_message(self, message):
+ raise AttributeError('''\
+eventlet.wsgi.server.log_message was deprecated and deleted.
+Please use server.log.info instead.''')
+
+
+try:
+ new = types.InstanceType
+except AttributeError:
+ new = lambda cls: cls.__new__(cls)
+
+
+try:
+ import ssl
+ ACCEPT_EXCEPTIONS = (socket.error, ssl.SSLError)
+ ACCEPT_ERRNO = set((errno.EPIPE, errno.EBADF, errno.ECONNRESET,
+ ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_SSL))
+except ImportError:
+ ACCEPT_EXCEPTIONS = (socket.error,)
+ ACCEPT_ERRNO = set((errno.EPIPE, errno.EBADF, errno.ECONNRESET))
+
+
+def socket_repr(sock):
+ scheme = 'http'
+ if hasattr(sock, 'do_handshake'):
+ scheme = 'https'
+
+ name = sock.getsockname()
+ if sock.family == socket.AF_INET:
+ hier_part = '//{0}:{1}'.format(*name)
+ elif sock.family == socket.AF_INET6:
+ hier_part = '//[{0}]:{1}'.format(*name[:2])
+ elif sock.family == socket.AF_UNIX:
+ hier_part = name
+ else:
+ hier_part = repr(name)
+
+ return scheme + ':' + hier_part
+
+
+def server(sock, site,
+ log=None,
+ environ=None,
+ max_size=None,
+ max_http_version=DEFAULT_MAX_HTTP_VERSION,
+ protocol=HttpProtocol,
+ server_event=None,
+ minimum_chunk_size=None,
+ log_x_forwarded_for=True,
+ custom_pool=None,
+ keepalive=True,
+ log_output=True,
+ log_format=DEFAULT_LOG_FORMAT,
+ url_length_limit=MAX_REQUEST_LINE,
+ debug=True,
+ socket_timeout=None,
+ capitalize_response_headers=True):
+ """Start up a WSGI server handling requests from the supplied server
+ socket. This function loops forever. The *sock* object will be
+ closed after server exits, but the underlying file descriptor will
+ remain open, so if you have a dup() of *sock*, it will remain usable.
+
+ .. warning::
+
+ At the moment :func:`server` will always wait for active connections to finish before
+ exiting, even if there's an exception raised inside it
+ (*all* exceptions are handled the same way, including :class:`greenlet.GreenletExit`
+ and those inheriting from `BaseException`).
+
+ While this may not be an issue normally, when it comes to long running HTTP connections
+ (like :mod:`eventlet.websocket`) it will become problematic and calling
+ :meth:`~eventlet.greenthread.GreenThread.wait` on a thread that runs the server may hang,
+ even after using :meth:`~eventlet.greenthread.GreenThread.kill`, as long
+ as there are active connections.
+
+ :param sock: Server socket, must be already bound to a port and listening.
+ :param site: WSGI application function.
+ :param log: logging.Logger instance or file-like object that logs should be written to.
+ If a Logger instance is supplied, messages are sent to the INFO log level.
+ If not specified, sys.stderr is used.
+ :param environ: Additional parameters that go into the environ dictionary of every request.
+ :param max_size: Maximum number of client connections opened at any time by this server.
+ Default is 1024.
+ :param max_http_version: Set to "HTTP/1.0" to make the server pretend it only supports HTTP 1.0.
+ This can help with applications or clients that don't behave properly using HTTP 1.1.
+ :param protocol: Protocol class. Deprecated.
+ :param server_event: Used to collect the Server object. Deprecated.
+ :param minimum_chunk_size: Minimum size in bytes for http chunks. This can be used to improve
+ performance of applications which yield many small strings, though
+ using it technically violates the WSGI spec. This can be overridden
+ on a per request basis by setting environ['eventlet.minimum_write_chunk_size'].
+ :param log_x_forwarded_for: If True (the default), logs the contents of the x-forwarded-for
+ header in addition to the actual client ip address in the 'client_ip' field of the
+ log line.
+ :param custom_pool: A custom GreenPool instance which is used to spawn client green threads.
+ If this is supplied, max_size is ignored.
+ :param keepalive: If set to False or zero, disables keepalives on the server; all connections
+ will be closed after serving one request. If numeric, it will be the timeout used
+ when reading the next request.
+ :param log_output: A Boolean indicating if the server will log data or not.
+ :param log_format: A python format string that is used as the template to generate log lines.
+ The following values can be formatted into it: client_ip, date_time, request_line,
+ status_code, body_length, wall_seconds. The default is a good example of how to
+ use it.
+ :param url_length_limit: A maximum allowed length of the request url. If exceeded, 414 error
+ is returned.
+ :param debug: True if the server should send exception tracebacks to the clients on 500 errors.
+ If False, the server will respond with empty bodies.
+ :param socket_timeout: Timeout for client connections' socket operations. Default None means
+ wait forever.
+ :param capitalize_response_headers: Normalize response headers' names to Foo-Bar.
+ Default is True.
+ """
+ serv = Server(
+ sock, sock.getsockname(),
+ site, log,
+ environ=environ,
+ max_http_version=max_http_version,
+ protocol=protocol,
+ minimum_chunk_size=minimum_chunk_size,
+ log_x_forwarded_for=log_x_forwarded_for,
+ keepalive=keepalive,
+ log_output=log_output,
+ log_format=log_format,
+ url_length_limit=url_length_limit,
+ debug=debug,
+ socket_timeout=socket_timeout,
+ capitalize_response_headers=capitalize_response_headers,
+ )
+ if server_event is not None:
+ warnings.warn(
+ 'eventlet.wsgi.Server() server_event kwarg is deprecated and will be removed soon',
+ DeprecationWarning, stacklevel=2)
+ server_event.send(serv)
+ if max_size is None:
+ max_size = DEFAULT_MAX_SIMULTANEOUS_REQUESTS
+ if custom_pool is not None:
+ pool = custom_pool
+ else:
+ pool = eventlet.GreenPool(max_size)
+
+ if not (hasattr(pool, 'spawn') and hasattr(pool, 'waitall')):
+ raise AttributeError('''\
+eventlet.wsgi.Server pool must provide methods: `spawn`, `waitall`.
+If unsure, use eventlet.GreenPool.''')
+
+ # [addr, socket, state]
+ connections = {}
+
+ def _clean_connection(_, conn):
+ connections.pop(conn[0], None)
+ conn[2] = STATE_CLOSE
+ greenio.shutdown_safe(conn[1])
+ conn[1].close()
+
+ try:
+ serv.log.info('({0}) wsgi starting up on {1}'.format(serv.pid, socket_repr(sock)))
+ while is_accepting:
+ try:
+ client_socket, client_addr = sock.accept()
+ client_socket.settimeout(serv.socket_timeout)
+ serv.log.debug('({0}) accepted {1!r}'.format(serv.pid, client_addr))
+ connections[client_addr] = connection = [client_addr, client_socket, STATE_IDLE]
+ (pool.spawn(serv.process_request, connection)
+ .link(_clean_connection, connection))
+ except ACCEPT_EXCEPTIONS as e:
+ if support.get_errno(e) not in ACCEPT_ERRNO:
+ raise
+ except (KeyboardInterrupt, SystemExit):
+ serv.log.info('wsgi exiting')
+ break
+ finally:
+ for cs in six.itervalues(connections):
+ prev_state = cs[2]
+ cs[2] = STATE_CLOSE
+ if prev_state == STATE_IDLE:
+ greenio.shutdown_safe(cs[1])
+ pool.waitall()
+ serv.log.info('({0}) wsgi exited, is_accepting={1}'.format(serv.pid, is_accepting))
+ try:
+ # NOTE: It's not clear whether we want this to leave the
+ # socket open or close it. Use cases like Spawning want
+ # the underlying fd to remain open, but if we're going
+ # that far we might as well not bother closing sock at
+ # all.
+ sock.close()
+ except socket.error as e:
+ if support.get_errno(e) not in BROKEN_SOCK:
+ traceback.print_exc()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..04033b670050419f5c80ab33020fa27ca53f14bd
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/METADATA
@@ -0,0 +1,56 @@
+Metadata-Version: 2.3
+Name: filelock
+Version: 3.14.0
+Summary: A platform independent file lock.
+Project-URL: Documentation, https://py-filelock.readthedocs.io
+Project-URL: Homepage, https://github.com/tox-dev/py-filelock
+Project-URL: Source, https://github.com/tox-dev/py-filelock
+Project-URL: Tracker, https://github.com/tox-dev/py-filelock/issues
+Maintainer-email: Bernát Gábor
+License-Expression: Unlicense
+License-File: LICENSE
+Keywords: application,cache,directory,log,user
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Topic :: Internet
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: System
+Requires-Python: >=3.8
+Provides-Extra: docs
+Requires-Dist: furo>=2023.9.10; extra == 'docs'
+Requires-Dist: sphinx-autodoc-typehints!=1.23.4,>=1.25.2; extra == 'docs'
+Requires-Dist: sphinx>=7.2.6; extra == 'docs'
+Provides-Extra: testing
+Requires-Dist: covdefaults>=2.3; extra == 'testing'
+Requires-Dist: coverage>=7.3.2; extra == 'testing'
+Requires-Dist: diff-cover>=8.0.1; extra == 'testing'
+Requires-Dist: pytest-cov>=4.1; extra == 'testing'
+Requires-Dist: pytest-mock>=3.12; extra == 'testing'
+Requires-Dist: pytest-timeout>=2.2; extra == 'testing'
+Requires-Dist: pytest>=7.4.3; extra == 'testing'
+Provides-Extra: typing
+Requires-Dist: typing-extensions>=4.8; (python_version < '3.11') and extra == 'typing'
+Description-Content-Type: text/markdown
+
+# filelock
+
+[](https://pypi.org/project/filelock/)
+[](https://pypi.org/project/filelock/)
+[](https://py-filelock.readthedocs.io/en/latest/?badge=latest)
+[](https://github.com/psf/black)
+[](https://pepy.tech/project/filelock)
+[](https://github.com/tox-dev/py-filelock/actions/workflows/check.yml)
+
+For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..f948190d044dbf0c0e92bd3227e93724f68e7e90
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/RECORD
@@ -0,0 +1,22 @@
+filelock-3.14.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+filelock-3.14.0.dist-info/METADATA,sha256=nSDS4Bqd1Rtvf-PB_bDjn0Dgu2kuL2GGCE1vM33KrlA,2792
+filelock-3.14.0.dist-info/RECORD,,
+filelock-3.14.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
+filelock-3.14.0.dist-info/licenses/LICENSE,sha256=iNm062BXnBkew5HKBMFhMFctfu3EqG2qWL8oxuFMm80,1210
+filelock/__init__.py,sha256=c_wPy9Fo0fmqE4V448Q2A2dDYnMTZeAVHX-kUoN3KCY,1214
+filelock/__pycache__/__init__.cpython-311.pyc,,
+filelock/__pycache__/_api.cpython-311.pyc,,
+filelock/__pycache__/_error.cpython-311.pyc,,
+filelock/__pycache__/_soft.cpython-311.pyc,,
+filelock/__pycache__/_unix.cpython-311.pyc,,
+filelock/__pycache__/_util.cpython-311.pyc,,
+filelock/__pycache__/_windows.cpython-311.pyc,,
+filelock/__pycache__/version.cpython-311.pyc,,
+filelock/_api.py,sha256=YrQpa5D3mB5VTEUZ8DHO1REvVu-WWmFRYgNaV3e6jOg,13028
+filelock/_error.py,sha256=-5jMcjTu60YAvAO1UbqDD1GIEjVkwr8xCFwDBtMeYDg,787
+filelock/_soft.py,sha256=haqtc_TB_KJbYv2a8iuEAclKuM4fMG1vTcp28sK919c,1711
+filelock/_unix.py,sha256=-FXP0tjInBHUYygOlMpp4taUmD87QOkrD_4ybg_iT7Q,2259
+filelock/_util.py,sha256=QHBoNFIYfbAThhotH3Q8E2acFc84wpG49-T-uu017ZE,1715
+filelock/_windows.py,sha256=eMKL8dZKrgekf5VYVGR14an29JGEInRtUO8ui9ABywg,2177
+filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+filelock/version.py,sha256=Ipjekae6alpGZC2b94mJAE2S2ZyJybTBe3oNCWsIFS4,413
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..516596c76787b10928cbab24f22c0ea00433b15d
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock-3.14.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.24.2
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..006299d2188c5d642cf78cf19305e88c95ee01cb
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/__init__.py
@@ -0,0 +1,52 @@
+"""
+A platform independent file lock that supports the with-statement.
+
+.. autodata:: filelock.__version__
+ :no-value:
+
+"""
+
+from __future__ import annotations
+
+import sys
+import warnings
+from typing import TYPE_CHECKING
+
+from ._api import AcquireReturnProxy, BaseFileLock
+from ._error import Timeout
+from ._soft import SoftFileLock
+from ._unix import UnixFileLock, has_fcntl
+from ._windows import WindowsFileLock
+from .version import version
+
+#: version of the project as a string
+__version__: str = version
+
+
+if sys.platform == "win32": # pragma: win32 cover
+ _FileLock: type[BaseFileLock] = WindowsFileLock
+else: # pragma: win32 no cover # noqa: PLR5501
+ if has_fcntl:
+ _FileLock: type[BaseFileLock] = UnixFileLock
+ else:
+ _FileLock = SoftFileLock
+ if warnings is not None:
+ warnings.warn("only soft file lock is available", stacklevel=2)
+
+if TYPE_CHECKING:
+ FileLock = SoftFileLock
+else:
+ #: Alias for the lock, which should be used for the current platform.
+ FileLock = _FileLock
+
+
+__all__ = [
+ "AcquireReturnProxy",
+ "BaseFileLock",
+ "FileLock",
+ "SoftFileLock",
+ "Timeout",
+ "UnixFileLock",
+ "WindowsFileLock",
+ "__version__",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_api.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd87972c7e1823c9a5cf43e13352d64caec36d34
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_api.py
@@ -0,0 +1,366 @@
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import time
+import warnings
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from threading import local
+from typing import TYPE_CHECKING, Any
+from weakref import WeakValueDictionary
+
+from ._error import Timeout
+
+if TYPE_CHECKING:
+ import sys
+ from types import TracebackType
+
+ if sys.version_info >= (3, 11): # pragma: no cover (py311+)
+ from typing import Self
+ else: # pragma: no cover ( None:
+ self.lock = lock
+
+ def __enter__(self) -> BaseFileLock:
+ return self.lock
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ self.lock.release()
+
+
+@dataclass
+class FileLockContext:
+ """A dataclass which holds the context for a ``BaseFileLock`` object."""
+
+ # The context is held in a separate class to allow optional use of thread local storage via the
+ # ThreadLocalFileContext class.
+
+ #: The path to the lock file.
+ lock_file: str
+
+ #: The default timeout value.
+ timeout: float
+
+ #: The mode for the lock files
+ mode: int
+
+ #: Whether the lock should be blocking or not
+ blocking: bool
+
+ #: The file descriptor for the *_lock_file* as it is returned by the os.open() function, not None when lock held
+ lock_file_fd: int | None = None
+
+ #: The lock counter is used for implementing the nested locking mechanism.
+ lock_counter: int = 0 # When the lock is acquired is increased and the lock is only released, when this value is 0
+
+
+class ThreadLocalFileContext(FileLockContext, local):
+ """A thread local version of the ``FileLockContext`` class."""
+
+
+class BaseFileLock(ABC, contextlib.ContextDecorator):
+ """Abstract base class for a file lock object."""
+
+ _instances: WeakValueDictionary[str, BaseFileLock]
+
+ def __new__( # noqa: PLR0913
+ cls,
+ lock_file: str | os.PathLike[str],
+ timeout: float = -1,
+ mode: int = 0o644,
+ thread_local: bool = True, # noqa: ARG003, FBT001, FBT002
+ *,
+ blocking: bool = True, # noqa: ARG003
+ is_singleton: bool = False,
+ **kwargs: dict[str, Any], # capture remaining kwargs for subclasses # noqa: ARG003
+ ) -> Self:
+ """Create a new lock object or if specified return the singleton instance for the lock file."""
+ if not is_singleton:
+ return super().__new__(cls)
+
+ instance = cls._instances.get(str(lock_file))
+ if not instance:
+ instance = super().__new__(cls)
+ cls._instances[str(lock_file)] = instance
+ elif timeout != instance.timeout or mode != instance.mode:
+ msg = "Singleton lock instances cannot be initialized with differing arguments"
+ raise ValueError(msg)
+
+ return instance # type: ignore[return-value] # https://github.com/python/mypy/issues/15322
+
+ def __init_subclass__(cls, **kwargs: dict[str, Any]) -> None:
+ """Setup unique state for lock subclasses."""
+ super().__init_subclass__(**kwargs)
+ cls._instances = WeakValueDictionary()
+
+ def __init__( # noqa: PLR0913
+ self,
+ lock_file: str | os.PathLike[str],
+ timeout: float = -1,
+ mode: int = 0o644,
+ thread_local: bool = True, # noqa: FBT001, FBT002
+ *,
+ blocking: bool = True,
+ is_singleton: bool = False,
+ ) -> None:
+ """
+ Create a new lock object.
+
+ :param lock_file: path to the file
+ :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in \
+ the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it \
+ to a negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
+ :param mode: file permissions for the lockfile
+ :param thread_local: Whether this object's internal context should be thread local or not. If this is set to \
+ ``False`` then the lock will be reentrant across threads.
+ :param blocking: whether the lock should be blocking or not
+ :param is_singleton: If this is set to ``True`` then only one instance of this class will be created \
+ per lock file. This is useful if you want to use the lock object for reentrant locking without needing \
+ to pass the same object around.
+
+ """
+ self._is_thread_local = thread_local
+ self._is_singleton = is_singleton
+
+ # Create the context. Note that external code should not work with the context directly and should instead use
+ # properties of this class.
+ kwargs: dict[str, Any] = {
+ "lock_file": os.fspath(lock_file),
+ "timeout": timeout,
+ "mode": mode,
+ "blocking": blocking,
+ }
+ self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs)
+
+ def is_thread_local(self) -> bool:
+ """:return: a flag indicating if this lock is thread local or not"""
+ return self._is_thread_local
+
+ @property
+ def is_singleton(self) -> bool:
+ """:return: a flag indicating if this lock is singleton or not"""
+ return self._is_singleton
+
+ @property
+ def lock_file(self) -> str:
+ """:return: path to the lock file"""
+ return self._context.lock_file
+
+ @property
+ def timeout(self) -> float:
+ """
+ :return: the default timeout value, in seconds
+
+ .. versionadded:: 2.0.0
+ """
+ return self._context.timeout
+
+ @timeout.setter
+ def timeout(self, value: float | str) -> None:
+ """
+ Change the default timeout value.
+
+ :param value: the new value, in seconds
+
+ """
+ self._context.timeout = float(value)
+
+ @property
+ def blocking(self) -> bool:
+ """:return: whether the locking is blocking or not"""
+ return self._context.blocking
+
+ @blocking.setter
+ def blocking(self, value: bool) -> None:
+ """
+ Change the default blocking value.
+
+ :param value: the new value as bool
+
+ """
+ self._context.blocking = value
+
+ @property
+ def mode(self) -> int:
+ """:return: the file permissions for the lockfile"""
+ return self._context.mode
+
+ @abstractmethod
+ def _acquire(self) -> None:
+ """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file."""
+ raise NotImplementedError
+
+ @abstractmethod
+ def _release(self) -> None:
+ """Releases the lock and sets self._context.lock_file_fd to None."""
+ raise NotImplementedError
+
+ @property
+ def is_locked(self) -> bool:
+ """
+
+ :return: A boolean indicating if the lock file is holding the lock currently.
+
+ .. versionchanged:: 2.0.0
+
+ This was previously a method and is now a property.
+ """
+ return self._context.lock_file_fd is not None
+
+ @property
+ def lock_counter(self) -> int:
+ """:return: The number of times this lock has been acquired (but not yet released)."""
+ return self._context.lock_counter
+
+ def acquire(
+ self,
+ timeout: float | None = None,
+ poll_interval: float = 0.05,
+ *,
+ poll_intervall: float | None = None,
+ blocking: bool | None = None,
+ ) -> AcquireReturnProxy:
+ """
+ Try to acquire the file lock.
+
+ :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and
+ if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired
+ :param poll_interval: interval of trying to acquire the lock file
+ :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead
+ :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
+ first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
+ :raises Timeout: if fails to acquire lock within the timeout period
+ :return: a context object that will unlock the file when the context is exited
+
+ .. code-block:: python
+
+ # You can use this method in the context manager (recommended)
+ with lock.acquire():
+ pass
+
+ # Or use an equivalent try-finally construct:
+ lock.acquire()
+ try:
+ pass
+ finally:
+ lock.release()
+
+ .. versionchanged:: 2.0.0
+
+ This method returns now a *proxy* object instead of *self*,
+ so that it can be used in a with statement without side effects.
+
+ """
+ # Use the default timeout, if no timeout is provided.
+ if timeout is None:
+ timeout = self._context.timeout
+
+ if blocking is None:
+ blocking = self._context.blocking
+
+ if poll_intervall is not None:
+ msg = "use poll_interval instead of poll_intervall"
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
+ poll_interval = poll_intervall
+
+ # Increment the number right at the beginning. We can still undo it, if something fails.
+ self._context.lock_counter += 1
+
+ lock_id = id(self)
+ lock_filename = self.lock_file
+ start_time = time.perf_counter()
+ try:
+ while True:
+ if not self.is_locked:
+ _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
+ self._acquire()
+ if self.is_locked:
+ _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
+ break
+ if blocking is False:
+ _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
+ raise Timeout(lock_filename) # noqa: TRY301
+ if 0 <= timeout < time.perf_counter() - start_time:
+ _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
+ raise Timeout(lock_filename) # noqa: TRY301
+ msg = "Lock %s not acquired on %s, waiting %s seconds ..."
+ _LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
+ time.sleep(poll_interval)
+ except BaseException: # Something did go wrong, so decrement the counter.
+ self._context.lock_counter = max(0, self._context.lock_counter - 1)
+ raise
+ return AcquireReturnProxy(lock=self)
+
+ def release(self, force: bool = False) -> None: # noqa: FBT001, FBT002
+ """
+ Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0.
+ Also note, that the lock file itself is not automatically deleted.
+
+ :param force: If true, the lock counter is ignored and the lock is released in every case/
+
+ """
+ if self.is_locked:
+ self._context.lock_counter -= 1
+
+ if self._context.lock_counter == 0 or force:
+ lock_id, lock_filename = id(self), self.lock_file
+
+ _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
+ self._release()
+ self._context.lock_counter = 0
+ _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
+
+ def __enter__(self) -> Self:
+ """
+ Acquire the lock.
+
+ :return: the lock object
+
+ """
+ self.acquire()
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ """
+ Release the lock.
+
+ :param exc_type: the exception type if raised
+ :param exc_value: the exception value if raised
+ :param traceback: the exception traceback if raised
+
+ """
+ self.release()
+
+ def __del__(self) -> None:
+ """Called when the lock object is deleted."""
+ self.release(force=True)
+
+
+__all__ = [
+ "AcquireReturnProxy",
+ "BaseFileLock",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_error.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7ff08c0f508ad7077eb6ed1990898840c952b3a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_error.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from typing import Any
+
+
+class Timeout(TimeoutError): # noqa: N818
+ """Raised when the lock could not be acquired in *timeout* seconds."""
+
+ def __init__(self, lock_file: str) -> None:
+ super().__init__()
+ self._lock_file = lock_file
+
+ def __reduce__(self) -> str | tuple[Any, ...]:
+ return self.__class__, (self._lock_file,) # Properly pickle the exception
+
+ def __str__(self) -> str:
+ return f"The file lock '{self._lock_file}' could not be acquired."
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}({self.lock_file!r})"
+
+ @property
+ def lock_file(self) -> str:
+ """:return: The path of the file lock."""
+ return self._lock_file
+
+
+__all__ = [
+ "Timeout",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_soft.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_soft.py
new file mode 100644
index 0000000000000000000000000000000000000000..28c67f74cc82b8f55e47afd6a71972cc1fb95eb6
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_soft.py
@@ -0,0 +1,47 @@
+from __future__ import annotations
+
+import os
+import sys
+from contextlib import suppress
+from errno import EACCES, EEXIST
+from pathlib import Path
+
+from ._api import BaseFileLock
+from ._util import ensure_directory_exists, raise_on_not_writable_file
+
+
+class SoftFileLock(BaseFileLock):
+ """Simply watches the existence of the lock file."""
+
+ def _acquire(self) -> None:
+ raise_on_not_writable_file(self.lock_file)
+ ensure_directory_exists(self.lock_file)
+ # first check for exists and read-only mode as the open will mask this case as EEXIST
+ flags = (
+ os.O_WRONLY # open for writing only
+ | os.O_CREAT
+ | os.O_EXCL # together with above raise EEXIST if the file specified by filename exists
+ | os.O_TRUNC # truncate the file to zero byte
+ )
+ try:
+ file_handler = os.open(self.lock_file, flags, self._context.mode)
+ except OSError as exception: # re-raise unless expected exception
+ if not (
+ exception.errno == EEXIST # lock already exist
+ or (exception.errno == EACCES and sys.platform == "win32") # has no access to this lock
+ ): # pragma: win32 no cover
+ raise
+ else:
+ self._context.lock_file_fd = file_handler
+
+ def _release(self) -> None:
+ assert self._context.lock_file_fd is not None # noqa: S101
+ os.close(self._context.lock_file_fd) # the lock file is definitely not None
+ self._context.lock_file_fd = None
+ with suppress(OSError): # the file is already deleted and that's what we want
+ Path(self.lock_file).unlink()
+
+
+__all__ = [
+ "SoftFileLock",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_unix.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_unix.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae1fbe916f95762418cd62251f91f74ba35fc8c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_unix.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+import os
+import sys
+from contextlib import suppress
+from errno import ENOSYS
+from pathlib import Path
+from typing import cast
+
+from ._api import BaseFileLock
+from ._util import ensure_directory_exists
+
+#: a flag to indicate if the fcntl API is available
+has_fcntl = False
+if sys.platform == "win32": # pragma: win32 cover
+
+ class UnixFileLock(BaseFileLock):
+ """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
+
+ def _acquire(self) -> None:
+ raise NotImplementedError
+
+ def _release(self) -> None:
+ raise NotImplementedError
+
+else: # pragma: win32 no cover
+ try:
+ import fcntl
+ except ImportError:
+ pass
+ else:
+ has_fcntl = True
+
+ class UnixFileLock(BaseFileLock):
+ """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
+
+ def _acquire(self) -> None:
+ ensure_directory_exists(self.lock_file)
+ open_flags = os.O_RDWR | os.O_TRUNC
+ if not Path(self.lock_file).exists():
+ open_flags |= os.O_CREAT
+ fd = os.open(self.lock_file, open_flags, self._context.mode)
+ with suppress(PermissionError): # This locked is not owned by this UID
+ os.fchmod(fd, self._context.mode)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as exception:
+ os.close(fd)
+ if exception.errno == ENOSYS: # NotImplemented error
+ msg = "FileSystem does not appear to support flock; use SoftFileLock instead"
+ raise NotImplementedError(msg) from exception
+ else:
+ self._context.lock_file_fd = fd
+
+ def _release(self) -> None:
+ # Do not remove the lockfile:
+ # https://github.com/tox-dev/py-filelock/issues/31
+ # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
+ fd = cast(int, self._context.lock_file_fd)
+ self._context.lock_file_fd = None
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ os.close(fd)
+
+
+__all__ = [
+ "UnixFileLock",
+ "has_fcntl",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_util.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..c671e8533873948f0e1b5575ff952c722019f067
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_util.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+import os
+import stat
+import sys
+from errno import EACCES, EISDIR
+from pathlib import Path
+
+
+def raise_on_not_writable_file(filename: str) -> None:
+ """
+ Raise an exception if attempting to open the file for writing would fail.
+
+ This is done so files that will never be writable can be separated from files that are writable but currently
+ locked.
+
+ :param filename: file to check
+ :raises OSError: as if the file was opened for writing.
+
+ """
+ try: # use stat to do exists + can write to check without race condition
+ file_stat = os.stat(filename) # noqa: PTH116
+ except OSError:
+ return # swallow does not exist or other errors
+
+ if file_stat.st_mtime != 0: # if os.stat returns but modification is zero that's an invalid os.stat - ignore it
+ if not (file_stat.st_mode & stat.S_IWUSR):
+ raise PermissionError(EACCES, "Permission denied", filename)
+
+ if stat.S_ISDIR(file_stat.st_mode):
+ if sys.platform == "win32": # pragma: win32 cover
+ # On Windows, this is PermissionError
+ raise PermissionError(EACCES, "Permission denied", filename)
+ else: # pragma: win32 no cover # noqa: RET506
+ # On linux / macOS, this is IsADirectoryError
+ raise IsADirectoryError(EISDIR, "Is a directory", filename)
+
+
+def ensure_directory_exists(filename: Path | str) -> None:
+ """
+ Ensure the directory containing the file exists (create it if necessary).
+
+ :param filename: file.
+
+ """
+ Path(filename).parent.mkdir(parents=True, exist_ok=True)
+
+
+__all__ = [
+ "ensure_directory_exists",
+ "raise_on_not_writable_file",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_windows.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..8db55dcbaa3e7bab091781b17ce22fde1fc239f2
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/_windows.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+import os
+import sys
+from contextlib import suppress
+from errno import EACCES
+from pathlib import Path
+from typing import cast
+
+from ._api import BaseFileLock
+from ._util import ensure_directory_exists, raise_on_not_writable_file
+
+if sys.platform == "win32": # pragma: win32 cover
+ import msvcrt
+
+ class WindowsFileLock(BaseFileLock):
+ """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""
+
+ def _acquire(self) -> None:
+ raise_on_not_writable_file(self.lock_file)
+ ensure_directory_exists(self.lock_file)
+ flags = (
+ os.O_RDWR # open for read and write
+ | os.O_CREAT # create file if not exists
+ | os.O_TRUNC # truncate file if not empty
+ )
+ try:
+ fd = os.open(self.lock_file, flags, self._context.mode)
+ except OSError as exception:
+ if exception.errno != EACCES: # has no access to this lock
+ raise
+ else:
+ try:
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ except OSError as exception:
+ os.close(fd) # close file first
+ if exception.errno != EACCES: # file is already locked
+ raise
+ else:
+ self._context.lock_file_fd = fd
+
+ def _release(self) -> None:
+ fd = cast(int, self._context.lock_file_fd)
+ self._context.lock_file_fd = None
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ os.close(fd)
+
+ with suppress(OSError): # Probably another instance of the application hat acquired the file lock.
+ Path(self.lock_file).unlink()
+
+else: # pragma: win32 no cover
+
+ class WindowsFileLock(BaseFileLock):
+ """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""
+
+ def _acquire(self) -> None:
+ raise NotImplementedError
+
+ def _release(self) -> None:
+ raise NotImplementedError
+
+
+__all__ = [
+ "WindowsFileLock",
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/py.typed b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..431bd6d819548f96e0edd905de41ea7e3a78a745
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/filelock/version.py
@@ -0,0 +1,16 @@
+# file generated by setuptools_scm
+# don't change, don't track in version control
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from typing import Tuple, Union
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
+else:
+ VERSION_TUPLE = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+
+__version__ = version = '3.14.0'
+__version_tuple__ = version_tuple = (3, 14, 0)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/LICENSE.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9d227a0cc43c3268d15722b763bd94ad298645a1
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/LICENSE.txt
@@ -0,0 +1,28 @@
+Copyright 2010 Pallets
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..5a02107246ee8047a2bd0b7ce221535a6bd23237
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/METADATA
@@ -0,0 +1,101 @@
+Metadata-Version: 2.1
+Name: Flask
+Version: 3.0.3
+Summary: A simple framework for building complex web applications.
+Maintainer-email: Pallets
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Web Environment
+Classifier: Framework :: Flask
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Internet :: WWW/HTTP :: WSGI
+Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
+Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
+Classifier: Typing :: Typed
+Requires-Dist: Werkzeug>=3.0.0
+Requires-Dist: Jinja2>=3.1.2
+Requires-Dist: itsdangerous>=2.1.2
+Requires-Dist: click>=8.1.3
+Requires-Dist: blinker>=1.6.2
+Requires-Dist: importlib-metadata>=3.6.0; python_version < '3.10'
+Requires-Dist: asgiref>=3.2 ; extra == "async"
+Requires-Dist: python-dotenv ; extra == "dotenv"
+Project-URL: Changes, https://flask.palletsprojects.com/changes/
+Project-URL: Chat, https://discord.gg/pallets
+Project-URL: Documentation, https://flask.palletsprojects.com/
+Project-URL: Donate, https://palletsprojects.com/donate
+Project-URL: Source, https://github.com/pallets/flask/
+Provides-Extra: async
+Provides-Extra: dotenv
+
+# Flask
+
+Flask is a lightweight [WSGI][] web application framework. It is designed
+to make getting started quick and easy, with the ability to scale up to
+complex applications. It began as a simple wrapper around [Werkzeug][]
+and [Jinja][], and has become one of the most popular Python web
+application frameworks.
+
+Flask offers suggestions, but doesn't enforce any dependencies or
+project layout. It is up to the developer to choose the tools and
+libraries they want to use. There are many extensions provided by the
+community that make adding new functionality easy.
+
+[WSGI]: https://wsgi.readthedocs.io/
+[Werkzeug]: https://werkzeug.palletsprojects.com/
+[Jinja]: https://jinja.palletsprojects.com/
+
+
+## Installing
+
+Install and update from [PyPI][] using an installer such as [pip][]:
+
+```
+$ pip install -U Flask
+```
+
+[PyPI]: https://pypi.org/project/Flask/
+[pip]: https://pip.pypa.io/en/stable/getting-started/
+
+
+## A Simple Example
+
+```python
+# save this as app.py
+from flask import Flask
+
+app = Flask(__name__)
+
+@app.route("/")
+def hello():
+ return "Hello, World!"
+```
+
+```
+$ flask run
+ * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
+```
+
+
+## Contributing
+
+For guidance on setting up a development environment and how to make a
+contribution to Flask, see the [contributing guidelines][].
+
+[contributing guidelines]: https://github.com/pallets/flask/blob/main/CONTRIBUTING.rst
+
+
+## Donate
+
+The Pallets organization develops and supports Flask and the libraries
+it uses. In order to grow the community of contributors and users, and
+allow the maintainers to devote more time to the projects, [please
+donate today][].
+
+[please donate today]: https://palletsprojects.com/donate
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..cf22a0050c6c0a0c94823a08e1b3b9f1c1935f43
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/RECORD
@@ -0,0 +1,58 @@
+../../Scripts/flask.exe,sha256=2ziPJ0IAemY1OXNqRR5k_D6TttQGMpGIVb6WrNqSlCA,108454
+flask-3.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+flask-3.0.3.dist-info/LICENSE.txt,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475
+flask-3.0.3.dist-info/METADATA,sha256=exPahy4aahjV-mYqd9qb5HNP8haB_IxTuaotoSvCtag,3177
+flask-3.0.3.dist-info/RECORD,,
+flask-3.0.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+flask-3.0.3.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
+flask-3.0.3.dist-info/entry_points.txt,sha256=bBP7hTOS5fz9zLtC7sPofBZAlMkEvBxu7KqS6l5lvc4,40
+flask/__init__.py,sha256=6xMqdVA0FIQ2U1KVaGX3lzNCdXPzoHPaa0hvQCNcfSk,2625
+flask/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
+flask/__pycache__/__init__.cpython-311.pyc,,
+flask/__pycache__/__main__.cpython-311.pyc,,
+flask/__pycache__/app.cpython-311.pyc,,
+flask/__pycache__/blueprints.cpython-311.pyc,,
+flask/__pycache__/cli.cpython-311.pyc,,
+flask/__pycache__/config.cpython-311.pyc,,
+flask/__pycache__/ctx.cpython-311.pyc,,
+flask/__pycache__/debughelpers.cpython-311.pyc,,
+flask/__pycache__/globals.cpython-311.pyc,,
+flask/__pycache__/helpers.cpython-311.pyc,,
+flask/__pycache__/logging.cpython-311.pyc,,
+flask/__pycache__/sessions.cpython-311.pyc,,
+flask/__pycache__/signals.cpython-311.pyc,,
+flask/__pycache__/templating.cpython-311.pyc,,
+flask/__pycache__/testing.cpython-311.pyc,,
+flask/__pycache__/typing.cpython-311.pyc,,
+flask/__pycache__/views.cpython-311.pyc,,
+flask/__pycache__/wrappers.cpython-311.pyc,,
+flask/app.py,sha256=7-lh6cIj27riTE1Q18Ok1p5nOZ8qYiMux4Btc6o6mNc,60143
+flask/blueprints.py,sha256=7INXPwTkUxfOQXOOv1yu52NpHPmPGI5fMTMFZ-BG9yY,4430
+flask/cli.py,sha256=OOaf_Efqih1i2in58j-5ZZZmQnPpaSfiUFbEjlL9bzw,35825
+flask/config.py,sha256=bLzLVAj-cq-Xotu9erqOFte0xSFaVXyfz0AkP4GbwmY,13312
+flask/ctx.py,sha256=4atDhJJ_cpV1VMq4qsfU4E_61M1oN93jlS2H9gjrl58,15120
+flask/debughelpers.py,sha256=PGIDhStW_efRjpaa3zHIpo-htStJOR41Ip3OJWPYBwo,6080
+flask/globals.py,sha256=XdQZmStBmPIs8t93tjx6pO7Bm3gobAaONWkFcUHaGas,1713
+flask/helpers.py,sha256=tYrcQ_73GuSZVEgwFr-eMmV69UriFQDBmt8wZJIAqvg,23084
+flask/json/__init__.py,sha256=hLNR898paqoefdeAhraa5wyJy-bmRB2k2dV4EgVy2Z8,5602
+flask/json/__pycache__/__init__.cpython-311.pyc,,
+flask/json/__pycache__/provider.cpython-311.pyc,,
+flask/json/__pycache__/tag.cpython-311.pyc,,
+flask/json/provider.py,sha256=q6iB83lSiopy80DZPrU-9mGcWwrD0mvLjiv9fHrRZgc,7646
+flask/json/tag.py,sha256=DhaNwuIOhdt2R74oOC9Y4Z8ZprxFYiRb5dUP5byyINw,9281
+flask/logging.py,sha256=8sM3WMTubi1cBb2c_lPkWpN0J8dMAqrgKRYLLi1dCVI,2377
+flask/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+flask/sansio/README.md,sha256=-0X1tECnilmz1cogx-YhNw5d7guK7GKrq_DEV2OzlU0,228
+flask/sansio/__pycache__/app.cpython-311.pyc,,
+flask/sansio/__pycache__/blueprints.cpython-311.pyc,,
+flask/sansio/__pycache__/scaffold.cpython-311.pyc,,
+flask/sansio/app.py,sha256=YG5Gf7JVf1c0yccWDZ86q5VSfJUidOVp27HFxFNxC7U,38053
+flask/sansio/blueprints.py,sha256=Tqe-7EkZ-tbWchm8iDoCfD848f0_3nLv6NNjeIPvHwM,24637
+flask/sansio/scaffold.py,sha256=WLV9TRQMMhGlXz-1OKtQ3lv6mtIBQZxdW2HezYrGxoI,30633
+flask/sessions.py,sha256=RU4lzm9MQW9CtH8rVLRTDm8USMJyT4LbvYe7sxM2__k,14807
+flask/signals.py,sha256=V7lMUww7CqgJ2ThUBn1PiatZtQanOyt7OZpu2GZI-34,750
+flask/templating.py,sha256=2TcXLT85Asflm2W9WOSFxKCmYn5e49w_Jkg9-NaaJWo,7537
+flask/testing.py,sha256=3BFXb3bP7R5r-XLBuobhczbxDu8-1LWRzYuhbr-lwaE,10163
+flask/typing.py,sha256=ZavK-wV28Yv8CQB7u73qZp_jLalpbWdrXS37QR1ftN0,3190
+flask/views.py,sha256=B66bTvYBBcHMYk4dA1ScZD0oTRTBl0I5smp1lRm9riI,6939
+flask/wrappers.py,sha256=m1j5tIJxIu8_sPPgTAB_G4TTh52Q-HoDuw_qHV5J59g,5831
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..3b5e64b5e6c4a210201d1676a891fd57b15cda99
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.9.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/entry_points.txt b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..eec6733e577feb9487435b9722713a820bd4ccc1
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask-3.0.3.dist-info/entry_points.txt
@@ -0,0 +1,3 @@
+[console_scripts]
+flask=flask.cli:main
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e86eb43ee989a2deb79eb064b5d3f1c71bb9d7cc
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/__init__.py
@@ -0,0 +1,60 @@
+from __future__ import annotations
+
+import typing as t
+
+from . import json as json
+from .app import Flask as Flask
+from .blueprints import Blueprint as Blueprint
+from .config import Config as Config
+from .ctx import after_this_request as after_this_request
+from .ctx import copy_current_request_context as copy_current_request_context
+from .ctx import has_app_context as has_app_context
+from .ctx import has_request_context as has_request_context
+from .globals import current_app as current_app
+from .globals import g as g
+from .globals import request as request
+from .globals import session as session
+from .helpers import abort as abort
+from .helpers import flash as flash
+from .helpers import get_flashed_messages as get_flashed_messages
+from .helpers import get_template_attribute as get_template_attribute
+from .helpers import make_response as make_response
+from .helpers import redirect as redirect
+from .helpers import send_file as send_file
+from .helpers import send_from_directory as send_from_directory
+from .helpers import stream_with_context as stream_with_context
+from .helpers import url_for as url_for
+from .json import jsonify as jsonify
+from .signals import appcontext_popped as appcontext_popped
+from .signals import appcontext_pushed as appcontext_pushed
+from .signals import appcontext_tearing_down as appcontext_tearing_down
+from .signals import before_render_template as before_render_template
+from .signals import got_request_exception as got_request_exception
+from .signals import message_flashed as message_flashed
+from .signals import request_finished as request_finished
+from .signals import request_started as request_started
+from .signals import request_tearing_down as request_tearing_down
+from .signals import template_rendered as template_rendered
+from .templating import render_template as render_template
+from .templating import render_template_string as render_template_string
+from .templating import stream_template as stream_template
+from .templating import stream_template_string as stream_template_string
+from .wrappers import Request as Request
+from .wrappers import Response as Response
+
+
+def __getattr__(name: str) -> t.Any:
+ if name == "__version__":
+ import importlib.metadata
+ import warnings
+
+ warnings.warn(
+ "The '__version__' attribute is deprecated and will be removed in"
+ " Flask 3.1. Use feature detection or"
+ " 'importlib.metadata.version(\"flask\")' instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return importlib.metadata.version("flask")
+
+ raise AttributeError(name)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/__main__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e28416e104515e90fca4b69cc60d0c61fd15d61
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/__main__.py
@@ -0,0 +1,3 @@
+from .cli import main
+
+main()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/app.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..7622b5e838d5b53bb00bd6ac6729707045cdcdbe
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/app.py
@@ -0,0 +1,1498 @@
+from __future__ import annotations
+
+import collections.abc as cabc
+import os
+import sys
+import typing as t
+import weakref
+from datetime import timedelta
+from inspect import iscoroutinefunction
+from itertools import chain
+from types import TracebackType
+from urllib.parse import quote as _url_quote
+
+import click
+from werkzeug.datastructures import Headers
+from werkzeug.datastructures import ImmutableDict
+from werkzeug.exceptions import BadRequestKeyError
+from werkzeug.exceptions import HTTPException
+from werkzeug.exceptions import InternalServerError
+from werkzeug.routing import BuildError
+from werkzeug.routing import MapAdapter
+from werkzeug.routing import RequestRedirect
+from werkzeug.routing import RoutingException
+from werkzeug.routing import Rule
+from werkzeug.serving import is_running_from_reloader
+from werkzeug.wrappers import Response as BaseResponse
+
+from . import cli
+from . import typing as ft
+from .ctx import AppContext
+from .ctx import RequestContext
+from .globals import _cv_app
+from .globals import _cv_request
+from .globals import current_app
+from .globals import g
+from .globals import request
+from .globals import request_ctx
+from .globals import session
+from .helpers import get_debug_flag
+from .helpers import get_flashed_messages
+from .helpers import get_load_dotenv
+from .helpers import send_from_directory
+from .sansio.app import App
+from .sansio.scaffold import _sentinel
+from .sessions import SecureCookieSessionInterface
+from .sessions import SessionInterface
+from .signals import appcontext_tearing_down
+from .signals import got_request_exception
+from .signals import request_finished
+from .signals import request_started
+from .signals import request_tearing_down
+from .templating import Environment
+from .wrappers import Request
+from .wrappers import Response
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from _typeshed.wsgi import StartResponse
+ from _typeshed.wsgi import WSGIEnvironment
+
+ from .testing import FlaskClient
+ from .testing import FlaskCliRunner
+
+T_shell_context_processor = t.TypeVar(
+ "T_shell_context_processor", bound=ft.ShellContextProcessorCallable
+)
+T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
+T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
+T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
+T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
+
+
+def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
+ if value is None or isinstance(value, timedelta):
+ return value
+
+ return timedelta(seconds=value)
+
+
+class Flask(App):
+ """The flask object implements a WSGI application and acts as the central
+ object. It is passed the name of the module or package of the
+ application. Once it is created it will act as a central registry for
+ the view functions, the URL rules, template configuration and much more.
+
+ The name of the package is used to resolve resources from inside the
+ package or the folder the module is contained in depending on if the
+ package parameter resolves to an actual python package (a folder with
+ an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
+
+ For more information about resource loading, see :func:`open_resource`.
+
+ Usually you create a :class:`Flask` instance in your main module or
+ in the :file:`__init__.py` file of your package like this::
+
+ from flask import Flask
+ app = Flask(__name__)
+
+ .. admonition:: About the First Parameter
+
+ The idea of the first parameter is to give Flask an idea of what
+ belongs to your application. This name is used to find resources
+ on the filesystem, can be used by extensions to improve debugging
+ information and a lot more.
+
+ So it's important what you provide there. If you are using a single
+ module, `__name__` is always the correct value. If you however are
+ using a package, it's usually recommended to hardcode the name of
+ your package there.
+
+ For example if your application is defined in :file:`yourapplication/app.py`
+ you should create it with one of the two versions below::
+
+ app = Flask('yourapplication')
+ app = Flask(__name__.split('.')[0])
+
+ Why is that? The application will work even with `__name__`, thanks
+ to how resources are looked up. However it will make debugging more
+ painful. Certain extensions can make assumptions based on the
+ import name of your application. For example the Flask-SQLAlchemy
+ extension will look for the code in your application that triggered
+ an SQL query in debug mode. If the import name is not properly set
+ up, that debugging information is lost. (For example it would only
+ pick up SQL queries in `yourapplication.app` and not
+ `yourapplication.views.frontend`)
+
+ .. versionadded:: 0.7
+ The `static_url_path`, `static_folder`, and `template_folder`
+ parameters were added.
+
+ .. versionadded:: 0.8
+ The `instance_path` and `instance_relative_config` parameters were
+ added.
+
+ .. versionadded:: 0.11
+ The `root_path` parameter was added.
+
+ .. versionadded:: 1.0
+ The ``host_matching`` and ``static_host`` parameters were added.
+
+ .. versionadded:: 1.0
+ The ``subdomain_matching`` parameter was added. Subdomain
+ matching needs to be enabled manually now. Setting
+ :data:`SERVER_NAME` does not implicitly enable it.
+
+ :param import_name: the name of the application package
+ :param static_url_path: can be used to specify a different path for the
+ static files on the web. Defaults to the name
+ of the `static_folder` folder.
+ :param static_folder: The folder with static files that is served at
+ ``static_url_path``. Relative to the application ``root_path``
+ or an absolute path. Defaults to ``'static'``.
+ :param static_host: the host to use when adding the static route.
+ Defaults to None. Required when using ``host_matching=True``
+ with a ``static_folder`` configured.
+ :param host_matching: set ``url_map.host_matching`` attribute.
+ Defaults to False.
+ :param subdomain_matching: consider the subdomain relative to
+ :data:`SERVER_NAME` when matching routes. Defaults to False.
+ :param template_folder: the folder that contains the templates that should
+ be used by the application. Defaults to
+ ``'templates'`` folder in the root path of the
+ application.
+ :param instance_path: An alternative instance path for the application.
+ By default the folder ``'instance'`` next to the
+ package or module is assumed to be the instance
+ path.
+ :param instance_relative_config: if set to ``True`` relative filenames
+ for loading the config are assumed to
+ be relative to the instance path instead
+ of the application root.
+ :param root_path: The path to the root of the application files.
+ This should only be set manually when it can't be detected
+ automatically, such as for namespace packages.
+ """
+
+ default_config = ImmutableDict(
+ {
+ "DEBUG": None,
+ "TESTING": False,
+ "PROPAGATE_EXCEPTIONS": None,
+ "SECRET_KEY": None,
+ "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
+ "USE_X_SENDFILE": False,
+ "SERVER_NAME": None,
+ "APPLICATION_ROOT": "/",
+ "SESSION_COOKIE_NAME": "session",
+ "SESSION_COOKIE_DOMAIN": None,
+ "SESSION_COOKIE_PATH": None,
+ "SESSION_COOKIE_HTTPONLY": True,
+ "SESSION_COOKIE_SECURE": False,
+ "SESSION_COOKIE_SAMESITE": None,
+ "SESSION_REFRESH_EACH_REQUEST": True,
+ "MAX_CONTENT_LENGTH": None,
+ "SEND_FILE_MAX_AGE_DEFAULT": None,
+ "TRAP_BAD_REQUEST_ERRORS": None,
+ "TRAP_HTTP_EXCEPTIONS": False,
+ "EXPLAIN_TEMPLATE_LOADING": False,
+ "PREFERRED_URL_SCHEME": "http",
+ "TEMPLATES_AUTO_RELOAD": None,
+ "MAX_COOKIE_SIZE": 4093,
+ }
+ )
+
+ #: The class that is used for request objects. See :class:`~flask.Request`
+ #: for more information.
+ request_class: type[Request] = Request
+
+ #: The class that is used for response objects. See
+ #: :class:`~flask.Response` for more information.
+ response_class: type[Response] = Response
+
+ #: the session interface to use. By default an instance of
+ #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
+ #:
+ #: .. versionadded:: 0.8
+ session_interface: SessionInterface = SecureCookieSessionInterface()
+
+ def __init__(
+ self,
+ import_name: str,
+ static_url_path: str | None = None,
+ static_folder: str | os.PathLike[str] | None = "static",
+ static_host: str | None = None,
+ host_matching: bool = False,
+ subdomain_matching: bool = False,
+ template_folder: str | os.PathLike[str] | None = "templates",
+ instance_path: str | None = None,
+ instance_relative_config: bool = False,
+ root_path: str | None = None,
+ ):
+ super().__init__(
+ import_name=import_name,
+ static_url_path=static_url_path,
+ static_folder=static_folder,
+ static_host=static_host,
+ host_matching=host_matching,
+ subdomain_matching=subdomain_matching,
+ template_folder=template_folder,
+ instance_path=instance_path,
+ instance_relative_config=instance_relative_config,
+ root_path=root_path,
+ )
+
+ #: The Click command group for registering CLI commands for this
+ #: object. The commands are available from the ``flask`` command
+ #: once the application has been discovered and blueprints have
+ #: been registered.
+ self.cli = cli.AppGroup()
+
+ # Set the name of the Click group in case someone wants to add
+ # the app's commands to another CLI tool.
+ self.cli.name = self.name
+
+ # Add a static route using the provided static_url_path, static_host,
+ # and static_folder if there is a configured static_folder.
+ # Note we do this without checking if static_folder exists.
+ # For one, it might be created while the server is running (e.g. during
+ # development). Also, Google App Engine stores static files somewhere
+ if self.has_static_folder:
+ assert (
+ bool(static_host) == host_matching
+ ), "Invalid static_host/host_matching combination"
+ # Use a weakref to avoid creating a reference cycle between the app
+ # and the view function (see #3761).
+ self_ref = weakref.ref(self)
+ self.add_url_rule(
+ f"{self.static_url_path}/",
+ endpoint="static",
+ host=static_host,
+ view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950
+ )
+
+ def get_send_file_max_age(self, filename: str | None) -> int | None:
+ """Used by :func:`send_file` to determine the ``max_age`` cache
+ value for a given file path if it wasn't passed.
+
+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
+ the configuration of :data:`~flask.current_app`. This defaults
+ to ``None``, which tells the browser to use conditional requests
+ instead of a timed cache, which is usually preferable.
+
+ Note this is a duplicate of the same method in the Flask
+ class.
+
+ .. versionchanged:: 2.0
+ The default configuration is ``None`` instead of 12 hours.
+
+ .. versionadded:: 0.9
+ """
+ value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
+
+ if value is None:
+ return None
+
+ if isinstance(value, timedelta):
+ return int(value.total_seconds())
+
+ return value # type: ignore[no-any-return]
+
+ def send_static_file(self, filename: str) -> Response:
+ """The view function used to serve files from
+ :attr:`static_folder`. A route is automatically registered for
+ this view at :attr:`static_url_path` if :attr:`static_folder` is
+ set.
+
+ Note this is a duplicate of the same method in the Flask
+ class.
+
+ .. versionadded:: 0.5
+
+ """
+ if not self.has_static_folder:
+ raise RuntimeError("'static_folder' must be set to serve static_files.")
+
+ # send_file only knows to call get_send_file_max_age on the app,
+ # call it here so it works for blueprints too.
+ max_age = self.get_send_file_max_age(filename)
+ return send_from_directory(
+ t.cast(str, self.static_folder), filename, max_age=max_age
+ )
+
+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
+ """Open a resource file relative to :attr:`root_path` for
+ reading.
+
+ For example, if the file ``schema.sql`` is next to the file
+ ``app.py`` where the ``Flask`` app is defined, it can be opened
+ with:
+
+ .. code-block:: python
+
+ with app.open_resource("schema.sql") as f:
+ conn.executescript(f.read())
+
+ :param resource: Path to the resource relative to
+ :attr:`root_path`.
+ :param mode: Open the file in this mode. Only reading is
+ supported, valid values are "r" (or "rt") and "rb".
+
+ Note this is a duplicate of the same method in the Flask
+ class.
+
+ """
+ if mode not in {"r", "rt", "rb"}:
+ raise ValueError("Resources can only be opened for reading.")
+
+ return open(os.path.join(self.root_path, resource), mode)
+
+ def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
+ """Opens a resource from the application's instance folder
+ (:attr:`instance_path`). Otherwise works like
+ :meth:`open_resource`. Instance resources can also be opened for
+ writing.
+
+ :param resource: the name of the resource. To access resources within
+ subfolders use forward slashes as separator.
+ :param mode: resource file opening mode, default is 'rb'.
+ """
+ return open(os.path.join(self.instance_path, resource), mode)
+
+ def create_jinja_environment(self) -> Environment:
+ """Create the Jinja environment based on :attr:`jinja_options`
+ and the various Jinja-related methods of the app. Changing
+ :attr:`jinja_options` after this will have no effect. Also adds
+ Flask-related globals and filters to the environment.
+
+ .. versionchanged:: 0.11
+ ``Environment.auto_reload`` set in accordance with
+ ``TEMPLATES_AUTO_RELOAD`` configuration option.
+
+ .. versionadded:: 0.5
+ """
+ options = dict(self.jinja_options)
+
+ if "autoescape" not in options:
+ options["autoescape"] = self.select_jinja_autoescape
+
+ if "auto_reload" not in options:
+ auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]
+
+ if auto_reload is None:
+ auto_reload = self.debug
+
+ options["auto_reload"] = auto_reload
+
+ rv = self.jinja_environment(self, **options)
+ rv.globals.update(
+ url_for=self.url_for,
+ get_flashed_messages=get_flashed_messages,
+ config=self.config,
+ # request, session and g are normally added with the
+ # context processor for efficiency reasons but for imported
+ # templates we also want the proxies in there.
+ request=request,
+ session=session,
+ g=g,
+ )
+ rv.policies["json.dumps_function"] = self.json.dumps
+ return rv
+
+ def create_url_adapter(self, request: Request | None) -> MapAdapter | None:
+ """Creates a URL adapter for the given request. The URL adapter
+ is created at a point where the request context is not yet set
+ up so the request is passed explicitly.
+
+ .. versionadded:: 0.6
+
+ .. versionchanged:: 0.9
+ This can now also be called without a request object when the
+ URL adapter is created for the application context.
+
+ .. versionchanged:: 1.0
+ :data:`SERVER_NAME` no longer implicitly enables subdomain
+ matching. Use :attr:`subdomain_matching` instead.
+ """
+ if request is not None:
+ # If subdomain matching is disabled (the default), use the
+ # default subdomain in all cases. This should be the default
+ # in Werkzeug but it currently does not have that feature.
+ if not self.subdomain_matching:
+ subdomain = self.url_map.default_subdomain or None
+ else:
+ subdomain = None
+
+ return self.url_map.bind_to_environ(
+ request.environ,
+ server_name=self.config["SERVER_NAME"],
+ subdomain=subdomain,
+ )
+ # We need at the very least the server name to be set for this
+ # to work.
+ if self.config["SERVER_NAME"] is not None:
+ return self.url_map.bind(
+ self.config["SERVER_NAME"],
+ script_name=self.config["APPLICATION_ROOT"],
+ url_scheme=self.config["PREFERRED_URL_SCHEME"],
+ )
+
+ return None
+
+ def raise_routing_exception(self, request: Request) -> t.NoReturn:
+ """Intercept routing exceptions and possibly do something else.
+
+ In debug mode, intercept a routing redirect and replace it with
+ an error if the body will be discarded.
+
+ With modern Werkzeug this shouldn't occur, since it now uses a
+ 308 status which tells the browser to resend the method and
+ body.
+
+ .. versionchanged:: 2.1
+ Don't intercept 307 and 308 redirects.
+
+ :meta private:
+ :internal:
+ """
+ if (
+ not self.debug
+ or not isinstance(request.routing_exception, RequestRedirect)
+ or request.routing_exception.code in {307, 308}
+ or request.method in {"GET", "HEAD", "OPTIONS"}
+ ):
+ raise request.routing_exception # type: ignore[misc]
+
+ from .debughelpers import FormDataRoutingRedirect
+
+ raise FormDataRoutingRedirect(request)
+
+ def update_template_context(self, context: dict[str, t.Any]) -> None:
+ """Update the template context with some commonly used variables.
+ This injects request, session, config and g into the template
+ context as well as everything template context processors want
+ to inject. Note that the as of Flask 0.6, the original values
+ in the context will not be overridden if a context processor
+ decides to return a value with the same key.
+
+ :param context: the context as a dictionary that is updated in place
+ to add extra variables.
+ """
+ names: t.Iterable[str | None] = (None,)
+
+ # A template may be rendered outside a request context.
+ if request:
+ names = chain(names, reversed(request.blueprints))
+
+ # The values passed to render_template take precedence. Keep a
+ # copy to re-apply after all context functions.
+ orig_ctx = context.copy()
+
+ for name in names:
+ if name in self.template_context_processors:
+ for func in self.template_context_processors[name]:
+ context.update(self.ensure_sync(func)())
+
+ context.update(orig_ctx)
+
+ def make_shell_context(self) -> dict[str, t.Any]:
+ """Returns the shell context for an interactive shell for this
+ application. This runs all the registered shell context
+ processors.
+
+ .. versionadded:: 0.11
+ """
+ rv = {"app": self, "g": g}
+ for processor in self.shell_context_processors:
+ rv.update(processor())
+ return rv
+
+ def run(
+ self,
+ host: str | None = None,
+ port: int | None = None,
+ debug: bool | None = None,
+ load_dotenv: bool = True,
+ **options: t.Any,
+ ) -> None:
+ """Runs the application on a local development server.
+
+ Do not use ``run()`` in a production setting. It is not intended to
+ meet security and performance requirements for a production server.
+ Instead, see :doc:`/deploying/index` for WSGI server recommendations.
+
+ If the :attr:`debug` flag is set the server will automatically reload
+ for code changes and show a debugger in case an exception happened.
+
+ If you want to run the application in debug mode, but disable the
+ code execution on the interactive debugger, you can pass
+ ``use_evalex=False`` as parameter. This will keep the debugger's
+ traceback screen active, but disable code execution.
+
+ It is not recommended to use this function for development with
+ automatic reloading as this is badly supported. Instead you should
+ be using the :command:`flask` command line script's ``run`` support.
+
+ .. admonition:: Keep in Mind
+
+ Flask will suppress any server error with a generic error page
+ unless it is in debug mode. As such to enable just the
+ interactive debugger without the code reloading, you have to
+ invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
+ Setting ``use_debugger`` to ``True`` without being in debug mode
+ won't catch any exceptions because there won't be any to
+ catch.
+
+ :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
+ have the server available externally as well. Defaults to
+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
+ if present.
+ :param port: the port of the webserver. Defaults to ``5000`` or the
+ port defined in the ``SERVER_NAME`` config variable if present.
+ :param debug: if given, enable or disable debug mode. See
+ :attr:`debug`.
+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
+ files to set environment variables. Will also change the working
+ directory to the directory containing the first file found.
+ :param options: the options to be forwarded to the underlying Werkzeug
+ server. See :func:`werkzeug.serving.run_simple` for more
+ information.
+
+ .. versionchanged:: 1.0
+ If installed, python-dotenv will be used to load environment
+ variables from :file:`.env` and :file:`.flaskenv` files.
+
+ The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.
+
+ Threaded mode is enabled by default.
+
+ .. versionchanged:: 0.10
+ The default port is now picked from the ``SERVER_NAME``
+ variable.
+ """
+ # Ignore this call so that it doesn't start another server if
+ # the 'flask run' command is used.
+ if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
+ if not is_running_from_reloader():
+ click.secho(
+ " * Ignoring a call to 'app.run()' that would block"
+ " the current 'flask' CLI command.\n"
+ " Only call 'app.run()' in an 'if __name__ =="
+ ' "__main__"\' guard.',
+ fg="red",
+ )
+
+ return
+
+ if get_load_dotenv(load_dotenv):
+ cli.load_dotenv()
+
+ # if set, env var overrides existing value
+ if "FLASK_DEBUG" in os.environ:
+ self.debug = get_debug_flag()
+
+ # debug passed to method overrides all other sources
+ if debug is not None:
+ self.debug = bool(debug)
+
+ server_name = self.config.get("SERVER_NAME")
+ sn_host = sn_port = None
+
+ if server_name:
+ sn_host, _, sn_port = server_name.partition(":")
+
+ if not host:
+ if sn_host:
+ host = sn_host
+ else:
+ host = "127.0.0.1"
+
+ if port or port == 0:
+ port = int(port)
+ elif sn_port:
+ port = int(sn_port)
+ else:
+ port = 5000
+
+ options.setdefault("use_reloader", self.debug)
+ options.setdefault("use_debugger", self.debug)
+ options.setdefault("threaded", True)
+
+ cli.show_server_banner(self.debug, self.name)
+
+ from werkzeug.serving import run_simple
+
+ try:
+ run_simple(t.cast(str, host), port, self, **options)
+ finally:
+ # reset the first request information if the development server
+ # reset normally. This makes it possible to restart the server
+ # without reloader and that stuff from an interactive shell.
+ self._got_first_request = False
+
+ def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:
+ """Creates a test client for this application. For information
+ about unit testing head over to :doc:`/testing`.
+
+ Note that if you are testing for assertions or exceptions in your
+ application code, you must set ``app.testing = True`` in order for the
+ exceptions to propagate to the test client. Otherwise, the exception
+ will be handled by the application (not visible to the test client) and
+ the only indication of an AssertionError or other exception will be a
+ 500 status code response to the test client. See the :attr:`testing`
+ attribute. For example::
+
+ app.testing = True
+ client = app.test_client()
+
+ The test client can be used in a ``with`` block to defer the closing down
+ of the context until the end of the ``with`` block. This is useful if
+ you want to access the context locals for testing::
+
+ with app.test_client() as c:
+ rv = c.get('/?vodka=42')
+ assert request.args['vodka'] == '42'
+
+ Additionally, you may pass optional keyword arguments that will then
+ be passed to the application's :attr:`test_client_class` constructor.
+ For example::
+
+ from flask.testing import FlaskClient
+
+ class CustomClient(FlaskClient):
+ def __init__(self, *args, **kwargs):
+ self._authentication = kwargs.pop("authentication")
+ super(CustomClient,self).__init__( *args, **kwargs)
+
+ app.test_client_class = CustomClient
+ client = app.test_client(authentication='Basic ....')
+
+ See :class:`~flask.testing.FlaskClient` for more information.
+
+ .. versionchanged:: 0.4
+ added support for ``with`` block usage for the client.
+
+ .. versionadded:: 0.7
+ The `use_cookies` parameter was added as well as the ability
+ to override the client to be used by setting the
+ :attr:`test_client_class` attribute.
+
+ .. versionchanged:: 0.11
+ Added `**kwargs` to support passing additional keyword arguments to
+ the constructor of :attr:`test_client_class`.
+ """
+ cls = self.test_client_class
+ if cls is None:
+ from .testing import FlaskClient as cls
+ return cls( # type: ignore
+ self, self.response_class, use_cookies=use_cookies, **kwargs
+ )
+
+ def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:
+ """Create a CLI runner for testing CLI commands.
+ See :ref:`testing-cli`.
+
+ Returns an instance of :attr:`test_cli_runner_class`, by default
+ :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
+ passed as the first argument.
+
+ .. versionadded:: 1.0
+ """
+ cls = self.test_cli_runner_class
+
+ if cls is None:
+ from .testing import FlaskCliRunner as cls
+
+ return cls(self, **kwargs) # type: ignore
+
+ def handle_http_exception(
+ self, e: HTTPException
+ ) -> HTTPException | ft.ResponseReturnValue:
+ """Handles an HTTP exception. By default this will invoke the
+ registered error handlers and fall back to returning the
+ exception as response.
+
+ .. versionchanged:: 1.0.3
+ ``RoutingException``, used internally for actions such as
+ slash redirects during routing, is not passed to error
+ handlers.
+
+ .. versionchanged:: 1.0
+ Exceptions are looked up by code *and* by MRO, so
+ ``HTTPException`` subclasses can be handled with a catch-all
+ handler for the base ``HTTPException``.
+
+ .. versionadded:: 0.3
+ """
+ # Proxy exceptions don't have error codes. We want to always return
+ # those unchanged as errors
+ if e.code is None:
+ return e
+
+ # RoutingExceptions are used internally to trigger routing
+ # actions, such as slash redirects raising RequestRedirect. They
+ # are not raised or handled in user code.
+ if isinstance(e, RoutingException):
+ return e
+
+ handler = self._find_error_handler(e, request.blueprints)
+ if handler is None:
+ return e
+ return self.ensure_sync(handler)(e) # type: ignore[no-any-return]
+
+ def handle_user_exception(
+ self, e: Exception
+ ) -> HTTPException | ft.ResponseReturnValue:
+ """This method is called whenever an exception occurs that
+ should be handled. A special case is :class:`~werkzeug
+ .exceptions.HTTPException` which is forwarded to the
+ :meth:`handle_http_exception` method. This function will either
+ return a response value or reraise the exception with the same
+ traceback.
+
+ .. versionchanged:: 1.0
+ Key errors raised from request data like ``form`` show the
+ bad key in debug mode rather than a generic bad request
+ message.
+
+ .. versionadded:: 0.7
+ """
+ if isinstance(e, BadRequestKeyError) and (
+ self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
+ ):
+ e.show_exception = True
+
+ if isinstance(e, HTTPException) and not self.trap_http_exception(e):
+ return self.handle_http_exception(e)
+
+ handler = self._find_error_handler(e, request.blueprints)
+
+ if handler is None:
+ raise
+
+ return self.ensure_sync(handler)(e) # type: ignore[no-any-return]
+
+ def handle_exception(self, e: Exception) -> Response:
+ """Handle an exception that did not have an error handler
+ associated with it, or that was raised from an error handler.
+ This always causes a 500 ``InternalServerError``.
+
+ Always sends the :data:`got_request_exception` signal.
+
+ If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug
+ mode, the error will be re-raised so that the debugger can
+ display it. Otherwise, the original exception is logged, and
+ an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
+
+ If an error handler is registered for ``InternalServerError`` or
+ ``500``, it will be used. For consistency, the handler will
+ always receive the ``InternalServerError``. The original
+ unhandled exception is available as ``e.original_exception``.
+
+ .. versionchanged:: 1.1.0
+ Always passes the ``InternalServerError`` instance to the
+ handler, setting ``original_exception`` to the unhandled
+ error.
+
+ .. versionchanged:: 1.1.0
+ ``after_request`` functions and other finalization is done
+ even for the default 500 response when there is no handler.
+
+ .. versionadded:: 0.3
+ """
+ exc_info = sys.exc_info()
+ got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)
+ propagate = self.config["PROPAGATE_EXCEPTIONS"]
+
+ if propagate is None:
+ propagate = self.testing or self.debug
+
+ if propagate:
+ # Re-raise if called with an active exception, otherwise
+ # raise the passed in exception.
+ if exc_info[1] is e:
+ raise
+
+ raise e
+
+ self.log_exception(exc_info)
+ server_error: InternalServerError | ft.ResponseReturnValue
+ server_error = InternalServerError(original_exception=e)
+ handler = self._find_error_handler(server_error, request.blueprints)
+
+ if handler is not None:
+ server_error = self.ensure_sync(handler)(server_error)
+
+ return self.finalize_request(server_error, from_error_handler=True)
+
+ def log_exception(
+ self,
+ exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),
+ ) -> None:
+ """Logs an exception. This is called by :meth:`handle_exception`
+ if debugging is disabled and right before the handler is called.
+ The default implementation logs the exception as error on the
+ :attr:`logger`.
+
+ .. versionadded:: 0.8
+ """
+ self.logger.error(
+ f"Exception on {request.path} [{request.method}]", exc_info=exc_info
+ )
+
+ def dispatch_request(self) -> ft.ResponseReturnValue:
+ """Does the request dispatching. Matches the URL and returns the
+ return value of the view or error handler. This does not have to
+ be a response object. In order to convert the return value to a
+ proper response object, call :func:`make_response`.
+
+ .. versionchanged:: 0.7
+ This no longer does the exception handling, this code was
+ moved to the new :meth:`full_dispatch_request`.
+ """
+ req = request_ctx.request
+ if req.routing_exception is not None:
+ self.raise_routing_exception(req)
+ rule: Rule = req.url_rule # type: ignore[assignment]
+ # if we provide automatic options for this URL and the
+ # request came with the OPTIONS method, reply automatically
+ if (
+ getattr(rule, "provide_automatic_options", False)
+ and req.method == "OPTIONS"
+ ):
+ return self.make_default_options_response()
+ # otherwise dispatch to the handler for that endpoint
+ view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]
+ return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]
+
+ def full_dispatch_request(self) -> Response:
+ """Dispatches the request and on top of that performs request
+ pre and postprocessing as well as HTTP exception catching and
+ error handling.
+
+ .. versionadded:: 0.7
+ """
+ self._got_first_request = True
+
+ try:
+ request_started.send(self, _async_wrapper=self.ensure_sync)
+ rv = self.preprocess_request()
+ if rv is None:
+ rv = self.dispatch_request()
+ except Exception as e:
+ rv = self.handle_user_exception(e)
+ return self.finalize_request(rv)
+
+ def finalize_request(
+ self,
+ rv: ft.ResponseReturnValue | HTTPException,
+ from_error_handler: bool = False,
+ ) -> Response:
+ """Given the return value from a view function this finalizes
+ the request by converting it into a response and invoking the
+ postprocessing functions. This is invoked for both normal
+ request dispatching as well as error handlers.
+
+ Because this means that it might be called as a result of a
+ failure a special safe mode is available which can be enabled
+ with the `from_error_handler` flag. If enabled, failures in
+ response processing will be logged and otherwise ignored.
+
+ :internal:
+ """
+ response = self.make_response(rv)
+ try:
+ response = self.process_response(response)
+ request_finished.send(
+ self, _async_wrapper=self.ensure_sync, response=response
+ )
+ except Exception:
+ if not from_error_handler:
+ raise
+ self.logger.exception(
+ "Request finalizing failed with an error while handling an error"
+ )
+ return response
+
+ def make_default_options_response(self) -> Response:
+ """This method is called to create the default ``OPTIONS`` response.
+ This can be changed through subclassing to change the default
+ behavior of ``OPTIONS`` responses.
+
+ .. versionadded:: 0.7
+ """
+ adapter = request_ctx.url_adapter
+ methods = adapter.allowed_methods() # type: ignore[union-attr]
+ rv = self.response_class()
+ rv.allow.update(methods)
+ return rv
+
+ def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
+ """Ensure that the function is synchronous for WSGI workers.
+ Plain ``def`` functions are returned as-is. ``async def``
+ functions are wrapped to run and wait for the response.
+
+ Override this method to change how the app runs async views.
+
+ .. versionadded:: 2.0
+ """
+ if iscoroutinefunction(func):
+ return self.async_to_sync(func)
+
+ return func
+
+ def async_to_sync(
+ self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]
+ ) -> t.Callable[..., t.Any]:
+ """Return a sync function that will run the coroutine function.
+
+ .. code-block:: python
+
+ result = app.async_to_sync(func)(*args, **kwargs)
+
+ Override this method to change how the app converts async code
+ to be synchronously callable.
+
+ .. versionadded:: 2.0
+ """
+ try:
+ from asgiref.sync import async_to_sync as asgiref_async_to_sync
+ except ImportError:
+ raise RuntimeError(
+ "Install Flask with the 'async' extra in order to use async views."
+ ) from None
+
+ return asgiref_async_to_sync(func)
+
+ def url_for(
+ self,
+ /,
+ endpoint: str,
+ *,
+ _anchor: str | None = None,
+ _method: str | None = None,
+ _scheme: str | None = None,
+ _external: bool | None = None,
+ **values: t.Any,
+ ) -> str:
+ """Generate a URL to the given endpoint with the given values.
+
+ This is called by :func:`flask.url_for`, and can be called
+ directly as well.
+
+ An *endpoint* is the name of a URL rule, usually added with
+ :meth:`@app.route() `, and usually the same name as the
+ view function. A route defined in a :class:`~flask.Blueprint`
+ will prepend the blueprint's name separated by a ``.`` to the
+ endpoint.
+
+ In some cases, such as email messages, you want URLs to include
+ the scheme and domain, like ``https://example.com/hello``. When
+ not in an active request, URLs will be external by default, but
+ this requires setting :data:`SERVER_NAME` so Flask knows what
+ domain to use. :data:`APPLICATION_ROOT` and
+ :data:`PREFERRED_URL_SCHEME` should also be configured as
+ needed. This config is only used when not in an active request.
+
+ Functions can be decorated with :meth:`url_defaults` to modify
+ keyword arguments before the URL is built.
+
+ If building fails for some reason, such as an unknown endpoint
+ or incorrect values, the app's :meth:`handle_url_build_error`
+ method is called. If that returns a string, that is returned,
+ otherwise a :exc:`~werkzeug.routing.BuildError` is raised.
+
+ :param endpoint: The endpoint name associated with the URL to
+ generate. If this starts with a ``.``, the current blueprint
+ name (if any) will be used.
+ :param _anchor: If given, append this as ``#anchor`` to the URL.
+ :param _method: If given, generate the URL associated with this
+ method for the endpoint.
+ :param _scheme: If given, the URL will have this scheme if it
+ is external.
+ :param _external: If given, prefer the URL to be internal
+ (False) or require it to be external (True). External URLs
+ include the scheme and domain. When not in an active
+ request, URLs are external by default.
+ :param values: Values to use for the variable parts of the URL
+ rule. Unknown keys are appended as query string arguments,
+ like ``?a=b&c=d``.
+
+ .. versionadded:: 2.2
+ Moved from ``flask.url_for``, which calls this method.
+ """
+ req_ctx = _cv_request.get(None)
+
+ if req_ctx is not None:
+ url_adapter = req_ctx.url_adapter
+ blueprint_name = req_ctx.request.blueprint
+
+ # If the endpoint starts with "." and the request matches a
+ # blueprint, the endpoint is relative to the blueprint.
+ if endpoint[:1] == ".":
+ if blueprint_name is not None:
+ endpoint = f"{blueprint_name}{endpoint}"
+ else:
+ endpoint = endpoint[1:]
+
+ # When in a request, generate a URL without scheme and
+ # domain by default, unless a scheme is given.
+ if _external is None:
+ _external = _scheme is not None
+ else:
+ app_ctx = _cv_app.get(None)
+
+ # If called by helpers.url_for, an app context is active,
+ # use its url_adapter. Otherwise, app.url_for was called
+ # directly, build an adapter.
+ if app_ctx is not None:
+ url_adapter = app_ctx.url_adapter
+ else:
+ url_adapter = self.create_url_adapter(None)
+
+ if url_adapter is None:
+ raise RuntimeError(
+ "Unable to build URLs outside an active request"
+ " without 'SERVER_NAME' configured. Also configure"
+ " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"
+ " needed."
+ )
+
+ # When outside a request, generate a URL with scheme and
+ # domain by default.
+ if _external is None:
+ _external = True
+
+ # It is an error to set _scheme when _external=False, in order
+ # to avoid accidental insecure URLs.
+ if _scheme is not None and not _external:
+ raise ValueError("When specifying '_scheme', '_external' must be True.")
+
+ self.inject_url_defaults(endpoint, values)
+
+ try:
+ rv = url_adapter.build( # type: ignore[union-attr]
+ endpoint,
+ values,
+ method=_method,
+ url_scheme=_scheme,
+ force_external=_external,
+ )
+ except BuildError as error:
+ values.update(
+ _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external
+ )
+ return self.handle_url_build_error(error, endpoint, values)
+
+ if _anchor is not None:
+ _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")
+ rv = f"{rv}#{_anchor}"
+
+ return rv
+
+ def make_response(self, rv: ft.ResponseReturnValue) -> Response:
+ """Convert the return value from a view function to an instance of
+ :attr:`response_class`.
+
+ :param rv: the return value from the view function. The view function
+ must return a response. Returning ``None``, or the view ending
+ without returning, is not allowed. The following types are allowed
+ for ``view_rv``:
+
+ ``str``
+ A response object is created with the string encoded to UTF-8
+ as the body.
+
+ ``bytes``
+ A response object is created with the bytes as the body.
+
+ ``dict``
+ A dictionary that will be jsonify'd before being returned.
+
+ ``list``
+ A list that will be jsonify'd before being returned.
+
+ ``generator`` or ``iterator``
+ A generator that returns ``str`` or ``bytes`` to be
+ streamed as the response.
+
+ ``tuple``
+ Either ``(body, status, headers)``, ``(body, status)``, or
+ ``(body, headers)``, where ``body`` is any of the other types
+ allowed here, ``status`` is a string or an integer, and
+ ``headers`` is a dictionary or a list of ``(key, value)``
+ tuples. If ``body`` is a :attr:`response_class` instance,
+ ``status`` overwrites the exiting value and ``headers`` are
+ extended.
+
+ :attr:`response_class`
+ The object is returned unchanged.
+
+ other :class:`~werkzeug.wrappers.Response` class
+ The object is coerced to :attr:`response_class`.
+
+ :func:`callable`
+ The function is called as a WSGI application. The result is
+ used to create a response object.
+
+ .. versionchanged:: 2.2
+ A generator will be converted to a streaming response.
+ A list will be converted to a JSON response.
+
+ .. versionchanged:: 1.1
+ A dict will be converted to a JSON response.
+
+ .. versionchanged:: 0.9
+ Previously a tuple was interpreted as the arguments for the
+ response object.
+ """
+
+ status = headers = None
+
+ # unpack tuple returns
+ if isinstance(rv, tuple):
+ len_rv = len(rv)
+
+ # a 3-tuple is unpacked directly
+ if len_rv == 3:
+ rv, status, headers = rv # type: ignore[misc]
+ # decide if a 2-tuple has status or headers
+ elif len_rv == 2:
+ if isinstance(rv[1], (Headers, dict, tuple, list)):
+ rv, headers = rv
+ else:
+ rv, status = rv # type: ignore[assignment,misc]
+ # other sized tuples are not allowed
+ else:
+ raise TypeError(
+ "The view function did not return a valid response tuple."
+ " The tuple must have the form (body, status, headers),"
+ " (body, status), or (body, headers)."
+ )
+
+ # the body must not be None
+ if rv is None:
+ raise TypeError(
+ f"The view function for {request.endpoint!r} did not"
+ " return a valid response. The function either returned"
+ " None or ended without a return statement."
+ )
+
+ # make sure the body is an instance of the response class
+ if not isinstance(rv, self.response_class):
+ if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):
+ # let the response class set the status and headers instead of
+ # waiting to do it manually, so that the class can handle any
+ # special logic
+ rv = self.response_class(
+ rv,
+ status=status,
+ headers=headers, # type: ignore[arg-type]
+ )
+ status = headers = None
+ elif isinstance(rv, (dict, list)):
+ rv = self.json.response(rv)
+ elif isinstance(rv, BaseResponse) or callable(rv):
+ # evaluate a WSGI callable, or coerce a different response
+ # class to the correct type
+ try:
+ rv = self.response_class.force_type(
+ rv, # type: ignore[arg-type]
+ request.environ,
+ )
+ except TypeError as e:
+ raise TypeError(
+ f"{e}\nThe view function did not return a valid"
+ " response. The return type must be a string,"
+ " dict, list, tuple with headers or status,"
+ " Response instance, or WSGI callable, but it"
+ f" was a {type(rv).__name__}."
+ ).with_traceback(sys.exc_info()[2]) from None
+ else:
+ raise TypeError(
+ "The view function did not return a valid"
+ " response. The return type must be a string,"
+ " dict, list, tuple with headers or status,"
+ " Response instance, or WSGI callable, but it was a"
+ f" {type(rv).__name__}."
+ )
+
+ rv = t.cast(Response, rv)
+ # prefer the status if it was provided
+ if status is not None:
+ if isinstance(status, (str, bytes, bytearray)):
+ rv.status = status
+ else:
+ rv.status_code = status
+
+ # extend existing headers with provided headers
+ if headers:
+ rv.headers.update(headers) # type: ignore[arg-type]
+
+ return rv
+
+ def preprocess_request(self) -> ft.ResponseReturnValue | None:
+ """Called before the request is dispatched. Calls
+ :attr:`url_value_preprocessors` registered with the app and the
+ current blueprint (if any). Then calls :attr:`before_request_funcs`
+ registered with the app and the blueprint.
+
+ If any :meth:`before_request` handler returns a non-None value, the
+ value is handled as if it was the return value from the view, and
+ further request handling is stopped.
+ """
+ names = (None, *reversed(request.blueprints))
+
+ for name in names:
+ if name in self.url_value_preprocessors:
+ for url_func in self.url_value_preprocessors[name]:
+ url_func(request.endpoint, request.view_args)
+
+ for name in names:
+ if name in self.before_request_funcs:
+ for before_func in self.before_request_funcs[name]:
+ rv = self.ensure_sync(before_func)()
+
+ if rv is not None:
+ return rv # type: ignore[no-any-return]
+
+ return None
+
+ def process_response(self, response: Response) -> Response:
+ """Can be overridden in order to modify the response object
+ before it's sent to the WSGI server. By default this will
+ call all the :meth:`after_request` decorated functions.
+
+ .. versionchanged:: 0.5
+ As of Flask 0.5 the functions registered for after request
+ execution are called in reverse order of registration.
+
+ :param response: a :attr:`response_class` object.
+ :return: a new response object or the same, has to be an
+ instance of :attr:`response_class`.
+ """
+ ctx = request_ctx._get_current_object() # type: ignore[attr-defined]
+
+ for func in ctx._after_request_functions:
+ response = self.ensure_sync(func)(response)
+
+ for name in chain(request.blueprints, (None,)):
+ if name in self.after_request_funcs:
+ for func in reversed(self.after_request_funcs[name]):
+ response = self.ensure_sync(func)(response)
+
+ if not self.session_interface.is_null_session(ctx.session):
+ self.session_interface.save_session(self, ctx.session, response)
+
+ return response
+
+ def do_teardown_request(
+ self,
+ exc: BaseException | None = _sentinel, # type: ignore[assignment]
+ ) -> None:
+ """Called after the request is dispatched and the response is
+ returned, right before the request context is popped.
+
+ This calls all functions decorated with
+ :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
+ if a blueprint handled the request. Finally, the
+ :data:`request_tearing_down` signal is sent.
+
+ This is called by
+ :meth:`RequestContext.pop() `,
+ which may be delayed during testing to maintain access to
+ resources.
+
+ :param exc: An unhandled exception raised while dispatching the
+ request. Detected from the current exception information if
+ not passed. Passed to each teardown function.
+
+ .. versionchanged:: 0.9
+ Added the ``exc`` argument.
+ """
+ if exc is _sentinel:
+ exc = sys.exc_info()[1]
+
+ for name in chain(request.blueprints, (None,)):
+ if name in self.teardown_request_funcs:
+ for func in reversed(self.teardown_request_funcs[name]):
+ self.ensure_sync(func)(exc)
+
+ request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
+
+ def do_teardown_appcontext(
+ self,
+ exc: BaseException | None = _sentinel, # type: ignore[assignment]
+ ) -> None:
+ """Called right before the application context is popped.
+
+ When handling a request, the application context is popped
+ after the request context. See :meth:`do_teardown_request`.
+
+ This calls all functions decorated with
+ :meth:`teardown_appcontext`. Then the
+ :data:`appcontext_tearing_down` signal is sent.
+
+ This is called by
+ :meth:`AppContext.pop() `.
+
+ .. versionadded:: 0.9
+ """
+ if exc is _sentinel:
+ exc = sys.exc_info()[1]
+
+ for func in reversed(self.teardown_appcontext_funcs):
+ self.ensure_sync(func)(exc)
+
+ appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
+
+ def app_context(self) -> AppContext:
+ """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
+ block to push the context, which will make :data:`current_app`
+ point at this application.
+
+ An application context is automatically pushed by
+ :meth:`RequestContext.push() `
+ when handling a request, and when running a CLI command. Use
+ this to manually create a context outside of these situations.
+
+ ::
+
+ with app.app_context():
+ init_db()
+
+ See :doc:`/appcontext`.
+
+ .. versionadded:: 0.9
+ """
+ return AppContext(self)
+
+ def request_context(self, environ: WSGIEnvironment) -> RequestContext:
+ """Create a :class:`~flask.ctx.RequestContext` representing a
+ WSGI environment. Use a ``with`` block to push the context,
+ which will make :data:`request` point at this request.
+
+ See :doc:`/reqcontext`.
+
+ Typically you should not call this from your own code. A request
+ context is automatically pushed by the :meth:`wsgi_app` when
+ handling a request. Use :meth:`test_request_context` to create
+ an environment and context instead of this method.
+
+ :param environ: a WSGI environment
+ """
+ return RequestContext(self, environ)
+
+ def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:
+ """Create a :class:`~flask.ctx.RequestContext` for a WSGI
+ environment created from the given values. This is mostly useful
+ during testing, where you may want to run a function that uses
+ request data without dispatching a full request.
+
+ See :doc:`/reqcontext`.
+
+ Use a ``with`` block to push the context, which will make
+ :data:`request` point at the request for the created
+ environment. ::
+
+ with app.test_request_context(...):
+ generate_report()
+
+ When using the shell, it may be easier to push and pop the
+ context manually to avoid indentation. ::
+
+ ctx = app.test_request_context(...)
+ ctx.push()
+ ...
+ ctx.pop()
+
+ Takes the same arguments as Werkzeug's
+ :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
+ the application. See the linked Werkzeug docs for most of the
+ available arguments. Flask-specific behavior is listed here.
+
+ :param path: URL path being requested.
+ :param base_url: Base URL where the app is being served, which
+ ``path`` is relative to. If not given, built from
+ :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
+ :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
+ :param subdomain: Subdomain name to append to
+ :data:`SERVER_NAME`.
+ :param url_scheme: Scheme to use instead of
+ :data:`PREFERRED_URL_SCHEME`.
+ :param data: The request body, either as a string or a dict of
+ form keys and values.
+ :param json: If given, this is serialized as JSON and passed as
+ ``data``. Also defaults ``content_type`` to
+ ``application/json``.
+ :param args: other positional arguments passed to
+ :class:`~werkzeug.test.EnvironBuilder`.
+ :param kwargs: other keyword arguments passed to
+ :class:`~werkzeug.test.EnvironBuilder`.
+ """
+ from .testing import EnvironBuilder
+
+ builder = EnvironBuilder(self, *args, **kwargs)
+
+ try:
+ return self.request_context(builder.get_environ())
+ finally:
+ builder.close()
+
+ def wsgi_app(
+ self, environ: WSGIEnvironment, start_response: StartResponse
+ ) -> cabc.Iterable[bytes]:
+ """The actual WSGI application. This is not implemented in
+ :meth:`__call__` so that middlewares can be applied without
+ losing a reference to the app object. Instead of doing this::
+
+ app = MyMiddleware(app)
+
+ It's a better idea to do this instead::
+
+ app.wsgi_app = MyMiddleware(app.wsgi_app)
+
+ Then you still have the original application object around and
+ can continue to call methods on it.
+
+ .. versionchanged:: 0.7
+ Teardown events for the request and app contexts are called
+ even if an unhandled error occurs. Other events may not be
+ called depending on when an error occurs during dispatch.
+ See :ref:`callbacks-and-errors`.
+
+ :param environ: A WSGI environment.
+ :param start_response: A callable accepting a status code,
+ a list of headers, and an optional exception context to
+ start the response.
+ """
+ ctx = self.request_context(environ)
+ error: BaseException | None = None
+ try:
+ try:
+ ctx.push()
+ response = self.full_dispatch_request()
+ except Exception as e:
+ error = e
+ response = self.handle_exception(e)
+ except: # noqa: B001
+ error = sys.exc_info()[1]
+ raise
+ return response(environ, start_response)
+ finally:
+ if "werkzeug.debug.preserve_context" in environ:
+ environ["werkzeug.debug.preserve_context"](_cv_app.get())
+ environ["werkzeug.debug.preserve_context"](_cv_request.get())
+
+ if error is not None and self.should_ignore_error(error):
+ error = None
+
+ ctx.pop(error)
+
+ def __call__(
+ self, environ: WSGIEnvironment, start_response: StartResponse
+ ) -> cabc.Iterable[bytes]:
+ """The WSGI server calls the Flask application object as the
+ WSGI application. This calls :meth:`wsgi_app`, which can be
+ wrapped to apply middleware.
+ """
+ return self.wsgi_app(environ, start_response)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/blueprints.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/blueprints.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa9eacf21b9e1a361ba3b3890173e8717a5b34aa
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/blueprints.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+
+import os
+import typing as t
+from datetime import timedelta
+
+from .cli import AppGroup
+from .globals import current_app
+from .helpers import send_from_directory
+from .sansio.blueprints import Blueprint as SansioBlueprint
+from .sansio.blueprints import BlueprintSetupState as BlueprintSetupState # noqa
+from .sansio.scaffold import _sentinel
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from .wrappers import Response
+
+
+class Blueprint(SansioBlueprint):
+ def __init__(
+ self,
+ name: str,
+ import_name: str,
+ static_folder: str | os.PathLike[str] | None = None,
+ static_url_path: str | None = None,
+ template_folder: str | os.PathLike[str] | None = None,
+ url_prefix: str | None = None,
+ subdomain: str | None = None,
+ url_defaults: dict[str, t.Any] | None = None,
+ root_path: str | None = None,
+ cli_group: str | None = _sentinel, # type: ignore
+ ) -> None:
+ super().__init__(
+ name,
+ import_name,
+ static_folder,
+ static_url_path,
+ template_folder,
+ url_prefix,
+ subdomain,
+ url_defaults,
+ root_path,
+ cli_group,
+ )
+
+ #: The Click command group for registering CLI commands for this
+ #: object. The commands are available from the ``flask`` command
+ #: once the application has been discovered and blueprints have
+ #: been registered.
+ self.cli = AppGroup()
+
+ # Set the name of the Click group in case someone wants to add
+ # the app's commands to another CLI tool.
+ self.cli.name = self.name
+
+ def get_send_file_max_age(self, filename: str | None) -> int | None:
+ """Used by :func:`send_file` to determine the ``max_age`` cache
+ value for a given file path if it wasn't passed.
+
+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
+ the configuration of :data:`~flask.current_app`. This defaults
+ to ``None``, which tells the browser to use conditional requests
+ instead of a timed cache, which is usually preferable.
+
+ Note this is a duplicate of the same method in the Flask
+ class.
+
+ .. versionchanged:: 2.0
+ The default configuration is ``None`` instead of 12 hours.
+
+ .. versionadded:: 0.9
+ """
+ value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
+
+ if value is None:
+ return None
+
+ if isinstance(value, timedelta):
+ return int(value.total_seconds())
+
+ return value # type: ignore[no-any-return]
+
+ def send_static_file(self, filename: str) -> Response:
+ """The view function used to serve files from
+ :attr:`static_folder`. A route is automatically registered for
+ this view at :attr:`static_url_path` if :attr:`static_folder` is
+ set.
+
+ Note this is a duplicate of the same method in the Flask
+ class.
+
+ .. versionadded:: 0.5
+
+ """
+ if not self.has_static_folder:
+ raise RuntimeError("'static_folder' must be set to serve static_files.")
+
+ # send_file only knows to call get_send_file_max_age on the app,
+ # call it here so it works for blueprints too.
+ max_age = self.get_send_file_max_age(filename)
+ return send_from_directory(
+ t.cast(str, self.static_folder), filename, max_age=max_age
+ )
+
+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
+ """Open a resource file relative to :attr:`root_path` for
+ reading.
+
+ For example, if the file ``schema.sql`` is next to the file
+ ``app.py`` where the ``Flask`` app is defined, it can be opened
+ with:
+
+ .. code-block:: python
+
+ with app.open_resource("schema.sql") as f:
+ conn.executescript(f.read())
+
+ :param resource: Path to the resource relative to
+ :attr:`root_path`.
+ :param mode: Open the file in this mode. Only reading is
+ supported, valid values are "r" (or "rt") and "rb".
+
+ Note this is a duplicate of the same method in the Flask
+ class.
+
+ """
+ if mode not in {"r", "rt", "rb"}:
+ raise ValueError("Resources can only be opened for reading.")
+
+ return open(os.path.join(self.root_path, resource), mode)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/cli.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecb292a01e9ef2456e27fa668eb43147bc96b3d9
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/cli.py
@@ -0,0 +1,1109 @@
+from __future__ import annotations
+
+import ast
+import collections.abc as cabc
+import importlib.metadata
+import inspect
+import os
+import platform
+import re
+import sys
+import traceback
+import typing as t
+from functools import update_wrapper
+from operator import itemgetter
+from types import ModuleType
+
+import click
+from click.core import ParameterSource
+from werkzeug import run_simple
+from werkzeug.serving import is_running_from_reloader
+from werkzeug.utils import import_string
+
+from .globals import current_app
+from .helpers import get_debug_flag
+from .helpers import get_load_dotenv
+
+if t.TYPE_CHECKING:
+ import ssl
+
+ from _typeshed.wsgi import StartResponse
+ from _typeshed.wsgi import WSGIApplication
+ from _typeshed.wsgi import WSGIEnvironment
+
+ from .app import Flask
+
+
+class NoAppException(click.UsageError):
+ """Raised if an application cannot be found or loaded."""
+
+
+def find_best_app(module: ModuleType) -> Flask:
+ """Given a module instance this tries to find the best possible
+ application in the module or raises an exception.
+ """
+ from . import Flask
+
+ # Search for the most common names first.
+ for attr_name in ("app", "application"):
+ app = getattr(module, attr_name, None)
+
+ if isinstance(app, Flask):
+ return app
+
+ # Otherwise find the only object that is a Flask instance.
+ matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]
+
+ if len(matches) == 1:
+ return matches[0]
+ elif len(matches) > 1:
+ raise NoAppException(
+ "Detected multiple Flask applications in module"
+ f" '{module.__name__}'. Use '{module.__name__}:name'"
+ " to specify the correct one."
+ )
+
+ # Search for app factory functions.
+ for attr_name in ("create_app", "make_app"):
+ app_factory = getattr(module, attr_name, None)
+
+ if inspect.isfunction(app_factory):
+ try:
+ app = app_factory()
+
+ if isinstance(app, Flask):
+ return app
+ except TypeError as e:
+ if not _called_with_wrong_args(app_factory):
+ raise
+
+ raise NoAppException(
+ f"Detected factory '{attr_name}' in module '{module.__name__}',"
+ " but could not call it without arguments. Use"
+ f" '{module.__name__}:{attr_name}(args)'"
+ " to specify arguments."
+ ) from e
+
+ raise NoAppException(
+ "Failed to find Flask application or factory in module"
+ f" '{module.__name__}'. Use '{module.__name__}:name'"
+ " to specify one."
+ )
+
+
+def _called_with_wrong_args(f: t.Callable[..., Flask]) -> bool:
+ """Check whether calling a function raised a ``TypeError`` because
+ the call failed or because something in the factory raised the
+ error.
+
+ :param f: The function that was called.
+ :return: ``True`` if the call failed.
+ """
+ tb = sys.exc_info()[2]
+
+ try:
+ while tb is not None:
+ if tb.tb_frame.f_code is f.__code__:
+ # In the function, it was called successfully.
+ return False
+
+ tb = tb.tb_next
+
+ # Didn't reach the function.
+ return True
+ finally:
+ # Delete tb to break a circular reference.
+ # https://docs.python.org/2/library/sys.html#sys.exc_info
+ del tb
+
+
+def find_app_by_string(module: ModuleType, app_name: str) -> Flask:
+ """Check if the given string is a variable name or a function. Call
+ a function to get the app instance, or return the variable directly.
+ """
+ from . import Flask
+
+ # Parse app_name as a single expression to determine if it's a valid
+ # attribute name or function call.
+ try:
+ expr = ast.parse(app_name.strip(), mode="eval").body
+ except SyntaxError:
+ raise NoAppException(
+ f"Failed to parse {app_name!r} as an attribute name or function call."
+ ) from None
+
+ if isinstance(expr, ast.Name):
+ name = expr.id
+ args = []
+ kwargs = {}
+ elif isinstance(expr, ast.Call):
+ # Ensure the function name is an attribute name only.
+ if not isinstance(expr.func, ast.Name):
+ raise NoAppException(
+ f"Function reference must be a simple name: {app_name!r}."
+ )
+
+ name = expr.func.id
+
+ # Parse the positional and keyword arguments as literals.
+ try:
+ args = [ast.literal_eval(arg) for arg in expr.args]
+ kwargs = {
+ kw.arg: ast.literal_eval(kw.value)
+ for kw in expr.keywords
+ if kw.arg is not None
+ }
+ except ValueError:
+ # literal_eval gives cryptic error messages, show a generic
+ # message with the full expression instead.
+ raise NoAppException(
+ f"Failed to parse arguments as literal values: {app_name!r}."
+ ) from None
+ else:
+ raise NoAppException(
+ f"Failed to parse {app_name!r} as an attribute name or function call."
+ )
+
+ try:
+ attr = getattr(module, name)
+ except AttributeError as e:
+ raise NoAppException(
+ f"Failed to find attribute {name!r} in {module.__name__!r}."
+ ) from e
+
+ # If the attribute is a function, call it with any args and kwargs
+ # to get the real application.
+ if inspect.isfunction(attr):
+ try:
+ app = attr(*args, **kwargs)
+ except TypeError as e:
+ if not _called_with_wrong_args(attr):
+ raise
+
+ raise NoAppException(
+ f"The factory {app_name!r} in module"
+ f" {module.__name__!r} could not be called with the"
+ " specified arguments."
+ ) from e
+ else:
+ app = attr
+
+ if isinstance(app, Flask):
+ return app
+
+ raise NoAppException(
+ "A valid Flask application was not obtained from"
+ f" '{module.__name__}:{app_name}'."
+ )
+
+
+def prepare_import(path: str) -> str:
+ """Given a filename this will try to calculate the python path, add it
+ to the search path and return the actual module name that is expected.
+ """
+ path = os.path.realpath(path)
+
+ fname, ext = os.path.splitext(path)
+ if ext == ".py":
+ path = fname
+
+ if os.path.basename(path) == "__init__":
+ path = os.path.dirname(path)
+
+ module_name = []
+
+ # move up until outside package structure (no __init__.py)
+ while True:
+ path, name = os.path.split(path)
+ module_name.append(name)
+
+ if not os.path.exists(os.path.join(path, "__init__.py")):
+ break
+
+ if sys.path[0] != path:
+ sys.path.insert(0, path)
+
+ return ".".join(module_name[::-1])
+
+
+@t.overload
+def locate_app(
+ module_name: str, app_name: str | None, raise_if_not_found: t.Literal[True] = True
+) -> Flask: ...
+
+
+@t.overload
+def locate_app(
+ module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ...
+) -> Flask | None: ...
+
+
+def locate_app(
+ module_name: str, app_name: str | None, raise_if_not_found: bool = True
+) -> Flask | None:
+ try:
+ __import__(module_name)
+ except ImportError:
+ # Reraise the ImportError if it occurred within the imported module.
+ # Determine this by checking whether the trace has a depth > 1.
+ if sys.exc_info()[2].tb_next: # type: ignore[union-attr]
+ raise NoAppException(
+ f"While importing {module_name!r}, an ImportError was"
+ f" raised:\n\n{traceback.format_exc()}"
+ ) from None
+ elif raise_if_not_found:
+ raise NoAppException(f"Could not import {module_name!r}.") from None
+ else:
+ return None
+
+ module = sys.modules[module_name]
+
+ if app_name is None:
+ return find_best_app(module)
+ else:
+ return find_app_by_string(module, app_name)
+
+
+def get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None:
+ if not value or ctx.resilient_parsing:
+ return
+
+ flask_version = importlib.metadata.version("flask")
+ werkzeug_version = importlib.metadata.version("werkzeug")
+
+ click.echo(
+ f"Python {platform.python_version()}\n"
+ f"Flask {flask_version}\n"
+ f"Werkzeug {werkzeug_version}",
+ color=ctx.color,
+ )
+ ctx.exit()
+
+
+version_option = click.Option(
+ ["--version"],
+ help="Show the Flask version.",
+ expose_value=False,
+ callback=get_version,
+ is_flag=True,
+ is_eager=True,
+)
+
+
+class ScriptInfo:
+ """Helper object to deal with Flask applications. This is usually not
+ necessary to interface with as it's used internally in the dispatching
+ to click. In future versions of Flask this object will most likely play
+ a bigger role. Typically it's created automatically by the
+ :class:`FlaskGroup` but you can also manually create it and pass it
+ onwards as click object.
+ """
+
+ def __init__(
+ self,
+ app_import_path: str | None = None,
+ create_app: t.Callable[..., Flask] | None = None,
+ set_debug_flag: bool = True,
+ ) -> None:
+ #: Optionally the import path for the Flask application.
+ self.app_import_path = app_import_path
+ #: Optionally a function that is passed the script info to create
+ #: the instance of the application.
+ self.create_app = create_app
+ #: A dictionary with arbitrary data that can be associated with
+ #: this script info.
+ self.data: dict[t.Any, t.Any] = {}
+ self.set_debug_flag = set_debug_flag
+ self._loaded_app: Flask | None = None
+
+ def load_app(self) -> Flask:
+ """Loads the Flask app (if not yet loaded) and returns it. Calling
+ this multiple times will just result in the already loaded app to
+ be returned.
+ """
+ if self._loaded_app is not None:
+ return self._loaded_app
+
+ if self.create_app is not None:
+ app: Flask | None = self.create_app()
+ else:
+ if self.app_import_path:
+ path, name = (
+ re.split(r":(?![\\/])", self.app_import_path, maxsplit=1) + [None]
+ )[:2]
+ import_name = prepare_import(path)
+ app = locate_app(import_name, name)
+ else:
+ for path in ("wsgi.py", "app.py"):
+ import_name = prepare_import(path)
+ app = locate_app(import_name, None, raise_if_not_found=False)
+
+ if app is not None:
+ break
+
+ if app is None:
+ raise NoAppException(
+ "Could not locate a Flask application. Use the"
+ " 'flask --app' option, 'FLASK_APP' environment"
+ " variable, or a 'wsgi.py' or 'app.py' file in the"
+ " current directory."
+ )
+
+ if self.set_debug_flag:
+ # Update the app's debug flag through the descriptor so that
+ # other values repopulate as well.
+ app.debug = get_debug_flag()
+
+ self._loaded_app = app
+ return app
+
+
+pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)
+
+F = t.TypeVar("F", bound=t.Callable[..., t.Any])
+
+
+def with_appcontext(f: F) -> F:
+ """Wraps a callback so that it's guaranteed to be executed with the
+ script's application context.
+
+ Custom commands (and their options) registered under ``app.cli`` or
+ ``blueprint.cli`` will always have an app context available, this
+ decorator is not required in that case.
+
+ .. versionchanged:: 2.2
+ The app context is active for subcommands as well as the
+ decorated callback. The app context is always available to
+ ``app.cli`` command and parameter callbacks.
+ """
+
+ @click.pass_context
+ def decorator(ctx: click.Context, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
+ if not current_app:
+ app = ctx.ensure_object(ScriptInfo).load_app()
+ ctx.with_resource(app.app_context())
+
+ return ctx.invoke(f, *args, **kwargs)
+
+ return update_wrapper(decorator, f) # type: ignore[return-value]
+
+
+class AppGroup(click.Group):
+ """This works similar to a regular click :class:`~click.Group` but it
+ changes the behavior of the :meth:`command` decorator so that it
+ automatically wraps the functions in :func:`with_appcontext`.
+
+ Not to be confused with :class:`FlaskGroup`.
+ """
+
+ def command( # type: ignore[override]
+ self, *args: t.Any, **kwargs: t.Any
+ ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:
+ """This works exactly like the method of the same name on a regular
+ :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
+ unless it's disabled by passing ``with_appcontext=False``.
+ """
+ wrap_for_ctx = kwargs.pop("with_appcontext", True)
+
+ def decorator(f: t.Callable[..., t.Any]) -> click.Command:
+ if wrap_for_ctx:
+ f = with_appcontext(f)
+ return super(AppGroup, self).command(*args, **kwargs)(f) # type: ignore[no-any-return]
+
+ return decorator
+
+ def group( # type: ignore[override]
+ self, *args: t.Any, **kwargs: t.Any
+ ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:
+ """This works exactly like the method of the same name on a regular
+ :class:`click.Group` but it defaults the group class to
+ :class:`AppGroup`.
+ """
+ kwargs.setdefault("cls", AppGroup)
+ return super().group(*args, **kwargs) # type: ignore[no-any-return]
+
+
+def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:
+ if value is None:
+ return None
+
+ info = ctx.ensure_object(ScriptInfo)
+ info.app_import_path = value
+ return value
+
+
+# This option is eager so the app will be available if --help is given.
+# --help is also eager, so --app must be before it in the param list.
+# no_args_is_help bypasses eager processing, so this option must be
+# processed manually in that case to ensure FLASK_APP gets picked up.
+_app_option = click.Option(
+ ["-A", "--app"],
+ metavar="IMPORT",
+ help=(
+ "The Flask application or factory function to load, in the form 'module:name'."
+ " Module can be a dotted import or file path. Name is not required if it is"
+ " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to"
+ " pass arguments."
+ ),
+ is_eager=True,
+ expose_value=False,
+ callback=_set_app,
+)
+
+
+def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:
+ # If the flag isn't provided, it will default to False. Don't use
+ # that, let debug be set by env in that case.
+ source = ctx.get_parameter_source(param.name) # type: ignore[arg-type]
+
+ if source is not None and source in (
+ ParameterSource.DEFAULT,
+ ParameterSource.DEFAULT_MAP,
+ ):
+ return None
+
+ # Set with env var instead of ScriptInfo.load so that it can be
+ # accessed early during a factory function.
+ os.environ["FLASK_DEBUG"] = "1" if value else "0"
+ return value
+
+
+_debug_option = click.Option(
+ ["--debug/--no-debug"],
+ help="Set debug mode.",
+ expose_value=False,
+ callback=_set_debug,
+)
+
+
+def _env_file_callback(
+ ctx: click.Context, param: click.Option, value: str | None
+) -> str | None:
+ if value is None:
+ return None
+
+ import importlib
+
+ try:
+ importlib.import_module("dotenv")
+ except ImportError:
+ raise click.BadParameter(
+ "python-dotenv must be installed to load an env file.",
+ ctx=ctx,
+ param=param,
+ ) from None
+
+ # Don't check FLASK_SKIP_DOTENV, that only disables automatically
+ # loading .env and .flaskenv files.
+ load_dotenv(value)
+ return value
+
+
+# This option is eager so env vars are loaded as early as possible to be
+# used by other options.
+_env_file_option = click.Option(
+ ["-e", "--env-file"],
+ type=click.Path(exists=True, dir_okay=False),
+ help="Load environment variables from this file. python-dotenv must be installed.",
+ is_eager=True,
+ expose_value=False,
+ callback=_env_file_callback,
+)
+
+
+class FlaskGroup(AppGroup):
+ """Special subclass of the :class:`AppGroup` group that supports
+ loading more commands from the configured Flask app. Normally a
+ developer does not have to interface with this class but there are
+ some very advanced use cases for which it makes sense to create an
+ instance of this. see :ref:`custom-scripts`.
+
+ :param add_default_commands: if this is True then the default run and
+ shell commands will be added.
+ :param add_version_option: adds the ``--version`` option.
+ :param create_app: an optional callback that is passed the script info and
+ returns the loaded app.
+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
+ files to set environment variables. Will also change the working
+ directory to the directory containing the first file found.
+ :param set_debug_flag: Set the app's debug flag.
+
+ .. versionchanged:: 2.2
+ Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.
+
+ .. versionchanged:: 2.2
+ An app context is pushed when running ``app.cli`` commands, so
+ ``@with_appcontext`` is no longer required for those commands.
+
+ .. versionchanged:: 1.0
+ If installed, python-dotenv will be used to load environment variables
+ from :file:`.env` and :file:`.flaskenv` files.
+ """
+
+ def __init__(
+ self,
+ add_default_commands: bool = True,
+ create_app: t.Callable[..., Flask] | None = None,
+ add_version_option: bool = True,
+ load_dotenv: bool = True,
+ set_debug_flag: bool = True,
+ **extra: t.Any,
+ ) -> None:
+ params = list(extra.pop("params", None) or ())
+ # Processing is done with option callbacks instead of a group
+ # callback. This allows users to make a custom group callback
+ # without losing the behavior. --env-file must come first so
+ # that it is eagerly evaluated before --app.
+ params.extend((_env_file_option, _app_option, _debug_option))
+
+ if add_version_option:
+ params.append(version_option)
+
+ if "context_settings" not in extra:
+ extra["context_settings"] = {}
+
+ extra["context_settings"].setdefault("auto_envvar_prefix", "FLASK")
+
+ super().__init__(params=params, **extra)
+
+ self.create_app = create_app
+ self.load_dotenv = load_dotenv
+ self.set_debug_flag = set_debug_flag
+
+ if add_default_commands:
+ self.add_command(run_command)
+ self.add_command(shell_command)
+ self.add_command(routes_command)
+
+ self._loaded_plugin_commands = False
+
+ def _load_plugin_commands(self) -> None:
+ if self._loaded_plugin_commands:
+ return
+
+ if sys.version_info >= (3, 10):
+ from importlib import metadata
+ else:
+ # Use a backport on Python < 3.10. We technically have
+ # importlib.metadata on 3.8+, but the API changed in 3.10,
+ # so use the backport for consistency.
+ import importlib_metadata as metadata
+
+ for ep in metadata.entry_points(group="flask.commands"):
+ self.add_command(ep.load(), ep.name)
+
+ self._loaded_plugin_commands = True
+
+ def get_command(self, ctx: click.Context, name: str) -> click.Command | None:
+ self._load_plugin_commands()
+ # Look up built-in and plugin commands, which should be
+ # available even if the app fails to load.
+ rv = super().get_command(ctx, name)
+
+ if rv is not None:
+ return rv
+
+ info = ctx.ensure_object(ScriptInfo)
+
+ # Look up commands provided by the app, showing an error and
+ # continuing if the app couldn't be loaded.
+ try:
+ app = info.load_app()
+ except NoAppException as e:
+ click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
+ return None
+
+ # Push an app context for the loaded app unless it is already
+ # active somehow. This makes the context available to parameter
+ # and command callbacks without needing @with_appcontext.
+ if not current_app or current_app._get_current_object() is not app: # type: ignore[attr-defined]
+ ctx.with_resource(app.app_context())
+
+ return app.cli.get_command(ctx, name)
+
+ def list_commands(self, ctx: click.Context) -> list[str]:
+ self._load_plugin_commands()
+ # Start with the built-in and plugin commands.
+ rv = set(super().list_commands(ctx))
+ info = ctx.ensure_object(ScriptInfo)
+
+ # Add commands provided by the app, showing an error and
+ # continuing if the app couldn't be loaded.
+ try:
+ rv.update(info.load_app().cli.list_commands(ctx))
+ except NoAppException as e:
+ # When an app couldn't be loaded, show the error message
+ # without the traceback.
+ click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
+ except Exception:
+ # When any other errors occurred during loading, show the
+ # full traceback.
+ click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")
+
+ return sorted(rv)
+
+ def make_context(
+ self,
+ info_name: str | None,
+ args: list[str],
+ parent: click.Context | None = None,
+ **extra: t.Any,
+ ) -> click.Context:
+ # Set a flag to tell app.run to become a no-op. If app.run was
+ # not in a __name__ == __main__ guard, it would start the server
+ # when importing, blocking whatever command is being called.
+ os.environ["FLASK_RUN_FROM_CLI"] = "true"
+
+ # Attempt to load .env and .flask env files. The --env-file
+ # option can cause another file to be loaded.
+ if get_load_dotenv(self.load_dotenv):
+ load_dotenv()
+
+ if "obj" not in extra and "obj" not in self.context_settings:
+ extra["obj"] = ScriptInfo(
+ create_app=self.create_app, set_debug_flag=self.set_debug_flag
+ )
+
+ return super().make_context(info_name, args, parent=parent, **extra)
+
+ def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
+ if not args and self.no_args_is_help:
+ # Attempt to load --env-file and --app early in case they
+ # were given as env vars. Otherwise no_args_is_help will not
+ # see commands from app.cli.
+ _env_file_option.handle_parse_result(ctx, {}, [])
+ _app_option.handle_parse_result(ctx, {}, [])
+
+ return super().parse_args(ctx, args)
+
+
+def _path_is_ancestor(path: str, other: str) -> bool:
+ """Take ``other`` and remove the length of ``path`` from it. Then join it
+ to ``path``. If it is the original value, ``path`` is an ancestor of
+ ``other``."""
+ return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other
+
+
+def load_dotenv(path: str | os.PathLike[str] | None = None) -> bool:
+ """Load "dotenv" files in order of precedence to set environment variables.
+
+ If an env var is already set it is not overwritten, so earlier files in the
+ list are preferred over later files.
+
+ This is a no-op if `python-dotenv`_ is not installed.
+
+ .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
+
+ :param path: Load the file at this location instead of searching.
+ :return: ``True`` if a file was loaded.
+
+ .. versionchanged:: 2.0
+ The current directory is not changed to the location of the
+ loaded file.
+
+ .. versionchanged:: 2.0
+ When loading the env files, set the default encoding to UTF-8.
+
+ .. versionchanged:: 1.1.0
+ Returns ``False`` when python-dotenv is not installed, or when
+ the given path isn't a file.
+
+ .. versionadded:: 1.0
+ """
+ try:
+ import dotenv
+ except ImportError:
+ if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):
+ click.secho(
+ " * Tip: There are .env or .flaskenv files present."
+ ' Do "pip install python-dotenv" to use them.',
+ fg="yellow",
+ err=True,
+ )
+
+ return False
+
+ # Always return after attempting to load a given path, don't load
+ # the default files.
+ if path is not None:
+ if os.path.isfile(path):
+ return dotenv.load_dotenv(path, encoding="utf-8")
+
+ return False
+
+ loaded = False
+
+ for name in (".env", ".flaskenv"):
+ path = dotenv.find_dotenv(name, usecwd=True)
+
+ if not path:
+ continue
+
+ dotenv.load_dotenv(path, encoding="utf-8")
+ loaded = True
+
+ return loaded # True if at least one file was located and loaded.
+
+
+def show_server_banner(debug: bool, app_import_path: str | None) -> None:
+ """Show extra startup messages the first time the server is run,
+ ignoring the reloader.
+ """
+ if is_running_from_reloader():
+ return
+
+ if app_import_path is not None:
+ click.echo(f" * Serving Flask app '{app_import_path}'")
+
+ if debug is not None:
+ click.echo(f" * Debug mode: {'on' if debug else 'off'}")
+
+
+class CertParamType(click.ParamType):
+ """Click option type for the ``--cert`` option. Allows either an
+ existing file, the string ``'adhoc'``, or an import for a
+ :class:`~ssl.SSLContext` object.
+ """
+
+ name = "path"
+
+ def __init__(self) -> None:
+ self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)
+
+ def convert(
+ self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None
+ ) -> t.Any:
+ try:
+ import ssl
+ except ImportError:
+ raise click.BadParameter(
+ 'Using "--cert" requires Python to be compiled with SSL support.',
+ ctx,
+ param,
+ ) from None
+
+ try:
+ return self.path_type(value, param, ctx)
+ except click.BadParameter:
+ value = click.STRING(value, param, ctx).lower()
+
+ if value == "adhoc":
+ try:
+ import cryptography # noqa: F401
+ except ImportError:
+ raise click.BadParameter(
+ "Using ad-hoc certificates requires the cryptography library.",
+ ctx,
+ param,
+ ) from None
+
+ return value
+
+ obj = import_string(value, silent=True)
+
+ if isinstance(obj, ssl.SSLContext):
+ return obj
+
+ raise
+
+
+def _validate_key(ctx: click.Context, param: click.Parameter, value: t.Any) -> t.Any:
+ """The ``--key`` option must be specified when ``--cert`` is a file.
+ Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
+ """
+ cert = ctx.params.get("cert")
+ is_adhoc = cert == "adhoc"
+
+ try:
+ import ssl
+ except ImportError:
+ is_context = False
+ else:
+ is_context = isinstance(cert, ssl.SSLContext)
+
+ if value is not None:
+ if is_adhoc:
+ raise click.BadParameter(
+ 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
+ )
+
+ if is_context:
+ raise click.BadParameter(
+ 'When "--cert" is an SSLContext object, "--key" is not used.',
+ ctx,
+ param,
+ )
+
+ if not cert:
+ raise click.BadParameter('"--cert" must also be specified.', ctx, param)
+
+ ctx.params["cert"] = cert, value
+
+ else:
+ if cert and not (is_adhoc or is_context):
+ raise click.BadParameter('Required when using "--cert".', ctx, param)
+
+ return value
+
+
+class SeparatedPathType(click.Path):
+ """Click option type that accepts a list of values separated by the
+ OS's path separator (``:``, ``;`` on Windows). Each value is
+ validated as a :class:`click.Path` type.
+ """
+
+ def convert(
+ self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None
+ ) -> t.Any:
+ items = self.split_envvar_value(value)
+ # can't call no-arg super() inside list comprehension until Python 3.12
+ super_convert = super().convert
+ return [super_convert(item, param, ctx) for item in items]
+
+
+@click.command("run", short_help="Run a development server.")
+@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")
+@click.option("--port", "-p", default=5000, help="The port to bind to.")
+@click.option(
+ "--cert",
+ type=CertParamType(),
+ help="Specify a certificate file to use HTTPS.",
+ is_eager=True,
+)
+@click.option(
+ "--key",
+ type=click.Path(exists=True, dir_okay=False, resolve_path=True),
+ callback=_validate_key,
+ expose_value=False,
+ help="The key file to use when specifying a certificate.",
+)
+@click.option(
+ "--reload/--no-reload",
+ default=None,
+ help="Enable or disable the reloader. By default the reloader "
+ "is active if debug is enabled.",
+)
+@click.option(
+ "--debugger/--no-debugger",
+ default=None,
+ help="Enable or disable the debugger. By default the debugger "
+ "is active if debug is enabled.",
+)
+@click.option(
+ "--with-threads/--without-threads",
+ default=True,
+ help="Enable or disable multithreading.",
+)
+@click.option(
+ "--extra-files",
+ default=None,
+ type=SeparatedPathType(),
+ help=(
+ "Extra files that trigger a reload on change. Multiple paths"
+ f" are separated by {os.path.pathsep!r}."
+ ),
+)
+@click.option(
+ "--exclude-patterns",
+ default=None,
+ type=SeparatedPathType(),
+ help=(
+ "Files matching these fnmatch patterns will not trigger a reload"
+ " on change. Multiple patterns are separated by"
+ f" {os.path.pathsep!r}."
+ ),
+)
+@pass_script_info
+def run_command(
+ info: ScriptInfo,
+ host: str,
+ port: int,
+ reload: bool,
+ debugger: bool,
+ with_threads: bool,
+ cert: ssl.SSLContext | tuple[str, str | None] | t.Literal["adhoc"] | None,
+ extra_files: list[str] | None,
+ exclude_patterns: list[str] | None,
+) -> None:
+ """Run a local development server.
+
+ This server is for development purposes only. It does not provide
+ the stability, security, or performance of production WSGI servers.
+
+ The reloader and debugger are enabled by default with the '--debug'
+ option.
+ """
+ try:
+ app: WSGIApplication = info.load_app()
+ except Exception as e:
+ if is_running_from_reloader():
+ # When reloading, print out the error immediately, but raise
+ # it later so the debugger or server can handle it.
+ traceback.print_exc()
+ err = e
+
+ def app(
+ environ: WSGIEnvironment, start_response: StartResponse
+ ) -> cabc.Iterable[bytes]:
+ raise err from None
+
+ else:
+ # When not reloading, raise the error immediately so the
+ # command fails.
+ raise e from None
+
+ debug = get_debug_flag()
+
+ if reload is None:
+ reload = debug
+
+ if debugger is None:
+ debugger = debug
+
+ show_server_banner(debug, info.app_import_path)
+
+ run_simple(
+ host,
+ port,
+ app,
+ use_reloader=reload,
+ use_debugger=debugger,
+ threaded=with_threads,
+ ssl_context=cert,
+ extra_files=extra_files,
+ exclude_patterns=exclude_patterns,
+ )
+
+
+run_command.params.insert(0, _debug_option)
+
+
+@click.command("shell", short_help="Run a shell in the app context.")
+@with_appcontext
+def shell_command() -> None:
+ """Run an interactive Python shell in the context of a given
+ Flask application. The application will populate the default
+ namespace of this shell according to its configuration.
+
+ This is useful for executing small snippets of management code
+ without having to manually configure the application.
+ """
+ import code
+
+ banner = (
+ f"Python {sys.version} on {sys.platform}\n"
+ f"App: {current_app.import_name}\n"
+ f"Instance: {current_app.instance_path}"
+ )
+ ctx: dict[str, t.Any] = {}
+
+ # Support the regular Python interpreter startup script if someone
+ # is using it.
+ startup = os.environ.get("PYTHONSTARTUP")
+ if startup and os.path.isfile(startup):
+ with open(startup) as f:
+ eval(compile(f.read(), startup, "exec"), ctx)
+
+ ctx.update(current_app.make_shell_context())
+
+ # Site, customize, or startup script can set a hook to call when
+ # entering interactive mode. The default one sets up readline with
+ # tab and history completion.
+ interactive_hook = getattr(sys, "__interactivehook__", None)
+
+ if interactive_hook is not None:
+ try:
+ import readline
+ from rlcompleter import Completer
+ except ImportError:
+ pass
+ else:
+ # rlcompleter uses __main__.__dict__ by default, which is
+ # flask.__main__. Use the shell context instead.
+ readline.set_completer(Completer(ctx).complete)
+
+ interactive_hook()
+
+ code.interact(banner=banner, local=ctx)
+
+
+@click.command("routes", short_help="Show the routes for the app.")
+@click.option(
+ "--sort",
+ "-s",
+ type=click.Choice(("endpoint", "methods", "domain", "rule", "match")),
+ default="endpoint",
+ help=(
+ "Method to sort routes by. 'match' is the order that Flask will match routes"
+ " when dispatching a request."
+ ),
+)
+@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")
+@with_appcontext
+def routes_command(sort: str, all_methods: bool) -> None:
+ """Show all registered routes with endpoints and methods."""
+ rules = list(current_app.url_map.iter_rules())
+
+ if not rules:
+ click.echo("No routes were registered.")
+ return
+
+ ignored_methods = set() if all_methods else {"HEAD", "OPTIONS"}
+ host_matching = current_app.url_map.host_matching
+ has_domain = any(rule.host if host_matching else rule.subdomain for rule in rules)
+ rows = []
+
+ for rule in rules:
+ row = [
+ rule.endpoint,
+ ", ".join(sorted((rule.methods or set()) - ignored_methods)),
+ ]
+
+ if has_domain:
+ row.append((rule.host if host_matching else rule.subdomain) or "")
+
+ row.append(rule.rule)
+ rows.append(row)
+
+ headers = ["Endpoint", "Methods"]
+ sorts = ["endpoint", "methods"]
+
+ if has_domain:
+ headers.append("Host" if host_matching else "Subdomain")
+ sorts.append("domain")
+
+ headers.append("Rule")
+ sorts.append("rule")
+
+ try:
+ rows.sort(key=itemgetter(sorts.index(sort)))
+ except ValueError:
+ pass
+
+ rows.insert(0, headers)
+ widths = [max(len(row[i]) for row in rows) for i in range(len(headers))]
+ rows.insert(1, ["-" * w for w in widths])
+ template = " ".join(f"{{{i}:<{w}}}" for i, w in enumerate(widths))
+
+ for row in rows:
+ click.echo(template.format(*row))
+
+
+cli = FlaskGroup(
+ name="flask",
+ help="""\
+A general utility script for Flask applications.
+
+An application to load must be given with the '--app' option,
+'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file
+in the current directory.
+""",
+)
+
+
+def main() -> None:
+ cli.main()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/config.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e3ba1790b635b2d9805bb408445fa2fc8fe344a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/config.py
@@ -0,0 +1,370 @@
+from __future__ import annotations
+
+import errno
+import json
+import os
+import types
+import typing as t
+
+from werkzeug.utils import import_string
+
+if t.TYPE_CHECKING:
+ import typing_extensions as te
+
+ from .sansio.app import App
+
+
+T = t.TypeVar("T")
+
+
+class ConfigAttribute(t.Generic[T]):
+ """Makes an attribute forward to the config"""
+
+ def __init__(
+ self, name: str, get_converter: t.Callable[[t.Any], T] | None = None
+ ) -> None:
+ self.__name__ = name
+ self.get_converter = get_converter
+
+ @t.overload
+ def __get__(self, obj: None, owner: None) -> te.Self: ...
+
+ @t.overload
+ def __get__(self, obj: App, owner: type[App]) -> T: ...
+
+ def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:
+ if obj is None:
+ return self
+
+ rv = obj.config[self.__name__]
+
+ if self.get_converter is not None:
+ rv = self.get_converter(rv)
+
+ return rv # type: ignore[no-any-return]
+
+ def __set__(self, obj: App, value: t.Any) -> None:
+ obj.config[self.__name__] = value
+
+
+class Config(dict): # type: ignore[type-arg]
+ """Works exactly like a dict but provides ways to fill it from files
+ or special dictionaries. There are two common patterns to populate the
+ config.
+
+ Either you can fill the config from a config file::
+
+ app.config.from_pyfile('yourconfig.cfg')
+
+ Or alternatively you can define the configuration options in the
+ module that calls :meth:`from_object` or provide an import path to
+ a module that should be loaded. It is also possible to tell it to
+ use the same module and with that provide the configuration values
+ just before the call::
+
+ DEBUG = True
+ SECRET_KEY = 'development key'
+ app.config.from_object(__name__)
+
+ In both cases (loading from any Python file or loading from modules),
+ only uppercase keys are added to the config. This makes it possible to use
+ lowercase values in the config file for temporary values that are not added
+ to the config or to define the config keys in the same file that implements
+ the application.
+
+ Probably the most interesting way to load configurations is from an
+ environment variable pointing to a file::
+
+ app.config.from_envvar('YOURAPPLICATION_SETTINGS')
+
+ In this case before launching the application you have to set this
+ environment variable to the file you want to use. On Linux and OS X
+ use the export statement::
+
+ export YOURAPPLICATION_SETTINGS='/path/to/config/file'
+
+ On windows use `set` instead.
+
+ :param root_path: path to which files are read relative from. When the
+ config object is created by the application, this is
+ the application's :attr:`~flask.Flask.root_path`.
+ :param defaults: an optional dictionary of default values
+ """
+
+ def __init__(
+ self,
+ root_path: str | os.PathLike[str],
+ defaults: dict[str, t.Any] | None = None,
+ ) -> None:
+ super().__init__(defaults or {})
+ self.root_path = root_path
+
+ def from_envvar(self, variable_name: str, silent: bool = False) -> bool:
+ """Loads a configuration from an environment variable pointing to
+ a configuration file. This is basically just a shortcut with nicer
+ error messages for this line of code::
+
+ app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
+
+ :param variable_name: name of the environment variable
+ :param silent: set to ``True`` if you want silent failure for missing
+ files.
+ :return: ``True`` if the file was loaded successfully.
+ """
+ rv = os.environ.get(variable_name)
+ if not rv:
+ if silent:
+ return False
+ raise RuntimeError(
+ f"The environment variable {variable_name!r} is not set"
+ " and as such configuration could not be loaded. Set"
+ " this variable and make it point to a configuration"
+ " file"
+ )
+ return self.from_pyfile(rv, silent=silent)
+
+ def from_prefixed_env(
+ self, prefix: str = "FLASK", *, loads: t.Callable[[str], t.Any] = json.loads
+ ) -> bool:
+ """Load any environment variables that start with ``FLASK_``,
+ dropping the prefix from the env key for the config key. Values
+ are passed through a loading function to attempt to convert them
+ to more specific types than strings.
+
+ Keys are loaded in :func:`sorted` order.
+
+ The default loading function attempts to parse values as any
+ valid JSON type, including dicts and lists.
+
+ Specific items in nested dicts can be set by separating the
+ keys with double underscores (``__``). If an intermediate key
+ doesn't exist, it will be initialized to an empty dict.
+
+ :param prefix: Load env vars that start with this prefix,
+ separated with an underscore (``_``).
+ :param loads: Pass each string value to this function and use
+ the returned value as the config value. If any error is
+ raised it is ignored and the value remains a string. The
+ default is :func:`json.loads`.
+
+ .. versionadded:: 2.1
+ """
+ prefix = f"{prefix}_"
+ len_prefix = len(prefix)
+
+ for key in sorted(os.environ):
+ if not key.startswith(prefix):
+ continue
+
+ value = os.environ[key]
+
+ try:
+ value = loads(value)
+ except Exception:
+ # Keep the value as a string if loading failed.
+ pass
+
+ # Change to key.removeprefix(prefix) on Python >= 3.9.
+ key = key[len_prefix:]
+
+ if "__" not in key:
+ # A non-nested key, set directly.
+ self[key] = value
+ continue
+
+ # Traverse nested dictionaries with keys separated by "__".
+ current = self
+ *parts, tail = key.split("__")
+
+ for part in parts:
+ # If an intermediate dict does not exist, create it.
+ if part not in current:
+ current[part] = {}
+
+ current = current[part]
+
+ current[tail] = value
+
+ return True
+
+ def from_pyfile(
+ self, filename: str | os.PathLike[str], silent: bool = False
+ ) -> bool:
+ """Updates the values in the config from a Python file. This function
+ behaves as if the file was imported as module with the
+ :meth:`from_object` function.
+
+ :param filename: the filename of the config. This can either be an
+ absolute filename or a filename relative to the
+ root path.
+ :param silent: set to ``True`` if you want silent failure for missing
+ files.
+ :return: ``True`` if the file was loaded successfully.
+
+ .. versionadded:: 0.7
+ `silent` parameter.
+ """
+ filename = os.path.join(self.root_path, filename)
+ d = types.ModuleType("config")
+ d.__file__ = filename
+ try:
+ with open(filename, mode="rb") as config_file:
+ exec(compile(config_file.read(), filename, "exec"), d.__dict__)
+ except OSError as e:
+ if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
+ return False
+ e.strerror = f"Unable to load configuration file ({e.strerror})"
+ raise
+ self.from_object(d)
+ return True
+
+ def from_object(self, obj: object | str) -> None:
+ """Updates the values from the given object. An object can be of one
+ of the following two types:
+
+ - a string: in this case the object with that name will be imported
+ - an actual object reference: that object is used directly
+
+ Objects are usually either modules or classes. :meth:`from_object`
+ loads only the uppercase attributes of the module/class. A ``dict``
+ object will not work with :meth:`from_object` because the keys of a
+ ``dict`` are not attributes of the ``dict`` class.
+
+ Example of module-based configuration::
+
+ app.config.from_object('yourapplication.default_config')
+ from yourapplication import default_config
+ app.config.from_object(default_config)
+
+ Nothing is done to the object before loading. If the object is a
+ class and has ``@property`` attributes, it needs to be
+ instantiated before being passed to this method.
+
+ You should not use this function to load the actual configuration but
+ rather configuration defaults. The actual config should be loaded
+ with :meth:`from_pyfile` and ideally from a location not within the
+ package because the package might be installed system wide.
+
+ See :ref:`config-dev-prod` for an example of class-based configuration
+ using :meth:`from_object`.
+
+ :param obj: an import name or object
+ """
+ if isinstance(obj, str):
+ obj = import_string(obj)
+ for key in dir(obj):
+ if key.isupper():
+ self[key] = getattr(obj, key)
+
+ def from_file(
+ self,
+ filename: str | os.PathLike[str],
+ load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],
+ silent: bool = False,
+ text: bool = True,
+ ) -> bool:
+ """Update the values in the config from a file that is loaded
+ using the ``load`` parameter. The loaded data is passed to the
+ :meth:`from_mapping` method.
+
+ .. code-block:: python
+
+ import json
+ app.config.from_file("config.json", load=json.load)
+
+ import tomllib
+ app.config.from_file("config.toml", load=tomllib.load, text=False)
+
+ :param filename: The path to the data file. This can be an
+ absolute path or relative to the config root path.
+ :param load: A callable that takes a file handle and returns a
+ mapping of loaded data from the file.
+ :type load: ``Callable[[Reader], Mapping]`` where ``Reader``
+ implements a ``read`` method.
+ :param silent: Ignore the file if it doesn't exist.
+ :param text: Open the file in text or binary mode.
+ :return: ``True`` if the file was loaded successfully.
+
+ .. versionchanged:: 2.3
+ The ``text`` parameter was added.
+
+ .. versionadded:: 2.0
+ """
+ filename = os.path.join(self.root_path, filename)
+
+ try:
+ with open(filename, "r" if text else "rb") as f:
+ obj = load(f)
+ except OSError as e:
+ if silent and e.errno in (errno.ENOENT, errno.EISDIR):
+ return False
+
+ e.strerror = f"Unable to load configuration file ({e.strerror})"
+ raise
+
+ return self.from_mapping(obj)
+
+ def from_mapping(
+ self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any
+ ) -> bool:
+ """Updates the config like :meth:`update` ignoring items with
+ non-upper keys.
+
+ :return: Always returns ``True``.
+
+ .. versionadded:: 0.11
+ """
+ mappings: dict[str, t.Any] = {}
+ if mapping is not None:
+ mappings.update(mapping)
+ mappings.update(kwargs)
+ for key, value in mappings.items():
+ if key.isupper():
+ self[key] = value
+ return True
+
+ def get_namespace(
+ self, namespace: str, lowercase: bool = True, trim_namespace: bool = True
+ ) -> dict[str, t.Any]:
+ """Returns a dictionary containing a subset of configuration options
+ that match the specified namespace/prefix. Example usage::
+
+ app.config['IMAGE_STORE_TYPE'] = 'fs'
+ app.config['IMAGE_STORE_PATH'] = '/var/app/images'
+ app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
+ image_store_config = app.config.get_namespace('IMAGE_STORE_')
+
+ The resulting dictionary `image_store_config` would look like::
+
+ {
+ 'type': 'fs',
+ 'path': '/var/app/images',
+ 'base_url': 'http://img.website.com'
+ }
+
+ This is often useful when configuration options map directly to
+ keyword arguments in functions or class constructors.
+
+ :param namespace: a configuration namespace
+ :param lowercase: a flag indicating if the keys of the resulting
+ dictionary should be lowercase
+ :param trim_namespace: a flag indicating if the keys of the resulting
+ dictionary should not include the namespace
+
+ .. versionadded:: 0.11
+ """
+ rv = {}
+ for k, v in self.items():
+ if not k.startswith(namespace):
+ continue
+ if trim_namespace:
+ key = k[len(namespace) :]
+ else:
+ key = k
+ if lowercase:
+ key = key.lower()
+ rv[key] = v
+ return rv
+
+ def __repr__(self) -> str:
+ return f"<{type(self).__name__} {dict.__repr__(self)}>"
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/ctx.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/ctx.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b164d3907106b459831ad27e539f98e2ea7f34c
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/ctx.py
@@ -0,0 +1,449 @@
+from __future__ import annotations
+
+import contextvars
+import sys
+import typing as t
+from functools import update_wrapper
+from types import TracebackType
+
+from werkzeug.exceptions import HTTPException
+
+from . import typing as ft
+from .globals import _cv_app
+from .globals import _cv_request
+from .signals import appcontext_popped
+from .signals import appcontext_pushed
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from _typeshed.wsgi import WSGIEnvironment
+
+ from .app import Flask
+ from .sessions import SessionMixin
+ from .wrappers import Request
+
+
+# a singleton sentinel value for parameter defaults
+_sentinel = object()
+
+
+class _AppCtxGlobals:
+ """A plain object. Used as a namespace for storing data during an
+ application context.
+
+ Creating an app context automatically creates this object, which is
+ made available as the :data:`g` proxy.
+
+ .. describe:: 'key' in g
+
+ Check whether an attribute is present.
+
+ .. versionadded:: 0.10
+
+ .. describe:: iter(g)
+
+ Return an iterator over the attribute names.
+
+ .. versionadded:: 0.10
+ """
+
+ # Define attr methods to let mypy know this is a namespace object
+ # that has arbitrary attributes.
+
+ def __getattr__(self, name: str) -> t.Any:
+ try:
+ return self.__dict__[name]
+ except KeyError:
+ raise AttributeError(name) from None
+
+ def __setattr__(self, name: str, value: t.Any) -> None:
+ self.__dict__[name] = value
+
+ def __delattr__(self, name: str) -> None:
+ try:
+ del self.__dict__[name]
+ except KeyError:
+ raise AttributeError(name) from None
+
+ def get(self, name: str, default: t.Any | None = None) -> t.Any:
+ """Get an attribute by name, or a default value. Like
+ :meth:`dict.get`.
+
+ :param name: Name of attribute to get.
+ :param default: Value to return if the attribute is not present.
+
+ .. versionadded:: 0.10
+ """
+ return self.__dict__.get(name, default)
+
+ def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:
+ """Get and remove an attribute by name. Like :meth:`dict.pop`.
+
+ :param name: Name of attribute to pop.
+ :param default: Value to return if the attribute is not present,
+ instead of raising a ``KeyError``.
+
+ .. versionadded:: 0.11
+ """
+ if default is _sentinel:
+ return self.__dict__.pop(name)
+ else:
+ return self.__dict__.pop(name, default)
+
+ def setdefault(self, name: str, default: t.Any = None) -> t.Any:
+ """Get the value of an attribute if it is present, otherwise
+ set and return a default value. Like :meth:`dict.setdefault`.
+
+ :param name: Name of attribute to get.
+ :param default: Value to set and return if the attribute is not
+ present.
+
+ .. versionadded:: 0.11
+ """
+ return self.__dict__.setdefault(name, default)
+
+ def __contains__(self, item: str) -> bool:
+ return item in self.__dict__
+
+ def __iter__(self) -> t.Iterator[str]:
+ return iter(self.__dict__)
+
+ def __repr__(self) -> str:
+ ctx = _cv_app.get(None)
+ if ctx is not None:
+ return f""
+ return object.__repr__(self)
+
+
+def after_this_request(
+ f: ft.AfterRequestCallable[t.Any],
+) -> ft.AfterRequestCallable[t.Any]:
+ """Executes a function after this request. This is useful to modify
+ response objects. The function is passed the response object and has
+ to return the same or a new one.
+
+ Example::
+
+ @app.route('/')
+ def index():
+ @after_this_request
+ def add_header(response):
+ response.headers['X-Foo'] = 'Parachute'
+ return response
+ return 'Hello World!'
+
+ This is more useful if a function other than the view function wants to
+ modify a response. For instance think of a decorator that wants to add
+ some headers without converting the return value into a response object.
+
+ .. versionadded:: 0.9
+ """
+ ctx = _cv_request.get(None)
+
+ if ctx is None:
+ raise RuntimeError(
+ "'after_this_request' can only be used when a request"
+ " context is active, such as in a view function."
+ )
+
+ ctx._after_request_functions.append(f)
+ return f
+
+
+F = t.TypeVar("F", bound=t.Callable[..., t.Any])
+
+
+def copy_current_request_context(f: F) -> F:
+ """A helper function that decorates a function to retain the current
+ request context. This is useful when working with greenlets. The moment
+ the function is decorated a copy of the request context is created and
+ then pushed when the function is called. The current session is also
+ included in the copied request context.
+
+ Example::
+
+ import gevent
+ from flask import copy_current_request_context
+
+ @app.route('/')
+ def index():
+ @copy_current_request_context
+ def do_some_work():
+ # do some work here, it can access flask.request or
+ # flask.session like you would otherwise in the view function.
+ ...
+ gevent.spawn(do_some_work)
+ return 'Regular response'
+
+ .. versionadded:: 0.10
+ """
+ ctx = _cv_request.get(None)
+
+ if ctx is None:
+ raise RuntimeError(
+ "'copy_current_request_context' can only be used when a"
+ " request context is active, such as in a view function."
+ )
+
+ ctx = ctx.copy()
+
+ def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
+ with ctx: # type: ignore[union-attr]
+ return ctx.app.ensure_sync(f)(*args, **kwargs) # type: ignore[union-attr]
+
+ return update_wrapper(wrapper, f) # type: ignore[return-value]
+
+
+def has_request_context() -> bool:
+ """If you have code that wants to test if a request context is there or
+ not this function can be used. For instance, you may want to take advantage
+ of request information if the request object is available, but fail
+ silently if it is unavailable.
+
+ ::
+
+ class User(db.Model):
+
+ def __init__(self, username, remote_addr=None):
+ self.username = username
+ if remote_addr is None and has_request_context():
+ remote_addr = request.remote_addr
+ self.remote_addr = remote_addr
+
+ Alternatively you can also just test any of the context bound objects
+ (such as :class:`request` or :class:`g`) for truthness::
+
+ class User(db.Model):
+
+ def __init__(self, username, remote_addr=None):
+ self.username = username
+ if remote_addr is None and request:
+ remote_addr = request.remote_addr
+ self.remote_addr = remote_addr
+
+ .. versionadded:: 0.7
+ """
+ return _cv_request.get(None) is not None
+
+
+def has_app_context() -> bool:
+ """Works like :func:`has_request_context` but for the application
+ context. You can also just do a boolean check on the
+ :data:`current_app` object instead.
+
+ .. versionadded:: 0.9
+ """
+ return _cv_app.get(None) is not None
+
+
+class AppContext:
+ """The app context contains application-specific information. An app
+ context is created and pushed at the beginning of each request if
+ one is not already active. An app context is also pushed when
+ running CLI commands.
+ """
+
+ def __init__(self, app: Flask) -> None:
+ self.app = app
+ self.url_adapter = app.create_url_adapter(None)
+ self.g: _AppCtxGlobals = app.app_ctx_globals_class()
+ self._cv_tokens: list[contextvars.Token[AppContext]] = []
+
+ def push(self) -> None:
+ """Binds the app context to the current context."""
+ self._cv_tokens.append(_cv_app.set(self))
+ appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)
+
+ def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore
+ """Pops the app context."""
+ try:
+ if len(self._cv_tokens) == 1:
+ if exc is _sentinel:
+ exc = sys.exc_info()[1]
+ self.app.do_teardown_appcontext(exc)
+ finally:
+ ctx = _cv_app.get()
+ _cv_app.reset(self._cv_tokens.pop())
+
+ if ctx is not self:
+ raise AssertionError(
+ f"Popped wrong app context. ({ctx!r} instead of {self!r})"
+ )
+
+ appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)
+
+ def __enter__(self) -> AppContext:
+ self.push()
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type | None,
+ exc_value: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.pop(exc_value)
+
+
+class RequestContext:
+ """The request context contains per-request information. The Flask
+ app creates and pushes it at the beginning of the request, then pops
+ it at the end of the request. It will create the URL adapter and
+ request object for the WSGI environment provided.
+
+ Do not attempt to use this class directly, instead use
+ :meth:`~flask.Flask.test_request_context` and
+ :meth:`~flask.Flask.request_context` to create this object.
+
+ When the request context is popped, it will evaluate all the
+ functions registered on the application for teardown execution
+ (:meth:`~flask.Flask.teardown_request`).
+
+ The request context is automatically popped at the end of the
+ request. When using the interactive debugger, the context will be
+ restored so ``request`` is still accessible. Similarly, the test
+ client can preserve the context after the request ends. However,
+ teardown functions may already have closed some resources such as
+ database connections.
+ """
+
+ def __init__(
+ self,
+ app: Flask,
+ environ: WSGIEnvironment,
+ request: Request | None = None,
+ session: SessionMixin | None = None,
+ ) -> None:
+ self.app = app
+ if request is None:
+ request = app.request_class(environ)
+ request.json_module = app.json
+ self.request: Request = request
+ self.url_adapter = None
+ try:
+ self.url_adapter = app.create_url_adapter(self.request)
+ except HTTPException as e:
+ self.request.routing_exception = e
+ self.flashes: list[tuple[str, str]] | None = None
+ self.session: SessionMixin | None = session
+ # Functions that should be executed after the request on the response
+ # object. These will be called before the regular "after_request"
+ # functions.
+ self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []
+
+ self._cv_tokens: list[
+ tuple[contextvars.Token[RequestContext], AppContext | None]
+ ] = []
+
+ def copy(self) -> RequestContext:
+ """Creates a copy of this request context with the same request object.
+ This can be used to move a request context to a different greenlet.
+ Because the actual request object is the same this cannot be used to
+ move a request context to a different thread unless access to the
+ request object is locked.
+
+ .. versionadded:: 0.10
+
+ .. versionchanged:: 1.1
+ The current session object is used instead of reloading the original
+ data. This prevents `flask.session` pointing to an out-of-date object.
+ """
+ return self.__class__(
+ self.app,
+ environ=self.request.environ,
+ request=self.request,
+ session=self.session,
+ )
+
+ def match_request(self) -> None:
+ """Can be overridden by a subclass to hook into the matching
+ of the request.
+ """
+ try:
+ result = self.url_adapter.match(return_rule=True) # type: ignore
+ self.request.url_rule, self.request.view_args = result # type: ignore
+ except HTTPException as e:
+ self.request.routing_exception = e
+
+ def push(self) -> None:
+ # Before we push the request context we have to ensure that there
+ # is an application context.
+ app_ctx = _cv_app.get(None)
+
+ if app_ctx is None or app_ctx.app is not self.app:
+ app_ctx = self.app.app_context()
+ app_ctx.push()
+ else:
+ app_ctx = None
+
+ self._cv_tokens.append((_cv_request.set(self), app_ctx))
+
+ # Open the session at the moment that the request context is available.
+ # This allows a custom open_session method to use the request context.
+ # Only open a new session if this is the first time the request was
+ # pushed, otherwise stream_with_context loses the session.
+ if self.session is None:
+ session_interface = self.app.session_interface
+ self.session = session_interface.open_session(self.app, self.request)
+
+ if self.session is None:
+ self.session = session_interface.make_null_session(self.app)
+
+ # Match the request URL after loading the session, so that the
+ # session is available in custom URL converters.
+ if self.url_adapter is not None:
+ self.match_request()
+
+ def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore
+ """Pops the request context and unbinds it by doing that. This will
+ also trigger the execution of functions registered by the
+ :meth:`~flask.Flask.teardown_request` decorator.
+
+ .. versionchanged:: 0.9
+ Added the `exc` argument.
+ """
+ clear_request = len(self._cv_tokens) == 1
+
+ try:
+ if clear_request:
+ if exc is _sentinel:
+ exc = sys.exc_info()[1]
+ self.app.do_teardown_request(exc)
+
+ request_close = getattr(self.request, "close", None)
+ if request_close is not None:
+ request_close()
+ finally:
+ ctx = _cv_request.get()
+ token, app_ctx = self._cv_tokens.pop()
+ _cv_request.reset(token)
+
+ # get rid of circular dependencies at the end of the request
+ # so that we don't require the GC to be active.
+ if clear_request:
+ ctx.request.environ["werkzeug.request"] = None
+
+ if app_ctx is not None:
+ app_ctx.pop(exc)
+
+ if ctx is not self:
+ raise AssertionError(
+ f"Popped wrong request context. ({ctx!r} instead of {self!r})"
+ )
+
+ def __enter__(self) -> RequestContext:
+ self.push()
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type | None,
+ exc_value: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.pop(exc_value)
+
+ def __repr__(self) -> str:
+ return (
+ f"<{type(self).__name__} {self.request.url!r}"
+ f" [{self.request.method}] of {self.app.name}>"
+ )
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/debughelpers.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/debughelpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c8c4c483677d2233f34baf82263d747f882d561
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/debughelpers.py
@@ -0,0 +1,178 @@
+from __future__ import annotations
+
+import typing as t
+
+from jinja2.loaders import BaseLoader
+from werkzeug.routing import RequestRedirect
+
+from .blueprints import Blueprint
+from .globals import request_ctx
+from .sansio.app import App
+
+if t.TYPE_CHECKING:
+ from .sansio.scaffold import Scaffold
+ from .wrappers import Request
+
+
+class UnexpectedUnicodeError(AssertionError, UnicodeError):
+ """Raised in places where we want some better error reporting for
+ unexpected unicode or binary data.
+ """
+
+
+class DebugFilesKeyError(KeyError, AssertionError):
+ """Raised from request.files during debugging. The idea is that it can
+ provide a better error message than just a generic KeyError/BadRequest.
+ """
+
+ def __init__(self, request: Request, key: str) -> None:
+ form_matches = request.form.getlist(key)
+ buf = [
+ f"You tried to access the file {key!r} in the request.files"
+ " dictionary but it does not exist. The mimetype for the"
+ f" request is {request.mimetype!r} instead of"
+ " 'multipart/form-data' which means that no file contents"
+ " were transmitted. To fix this error you should provide"
+ ' enctype="multipart/form-data" in your form.'
+ ]
+ if form_matches:
+ names = ", ".join(repr(x) for x in form_matches)
+ buf.append(
+ "\n\nThe browser instead transmitted some file names. "
+ f"This was submitted: {names}"
+ )
+ self.msg = "".join(buf)
+
+ def __str__(self) -> str:
+ return self.msg
+
+
+class FormDataRoutingRedirect(AssertionError):
+ """This exception is raised in debug mode if a routing redirect
+ would cause the browser to drop the method or body. This happens
+ when method is not GET, HEAD or OPTIONS and the status code is not
+ 307 or 308.
+ """
+
+ def __init__(self, request: Request) -> None:
+ exc = request.routing_exception
+ assert isinstance(exc, RequestRedirect)
+ buf = [
+ f"A request was sent to '{request.url}', but routing issued"
+ f" a redirect to the canonical URL '{exc.new_url}'."
+ ]
+
+ if f"{request.base_url}/" == exc.new_url.partition("?")[0]:
+ buf.append(
+ " The URL was defined with a trailing slash. Flask"
+ " will redirect to the URL with a trailing slash if it"
+ " was accessed without one."
+ )
+
+ buf.append(
+ " Send requests to the canonical URL, or use 307 or 308 for"
+ " routing redirects. Otherwise, browsers will drop form"
+ " data.\n\n"
+ "This exception is only raised in debug mode."
+ )
+ super().__init__("".join(buf))
+
+
+def attach_enctype_error_multidict(request: Request) -> None:
+ """Patch ``request.files.__getitem__`` to raise a descriptive error
+ about ``enctype=multipart/form-data``.
+
+ :param request: The request to patch.
+ :meta private:
+ """
+ oldcls = request.files.__class__
+
+ class newcls(oldcls): # type: ignore[valid-type, misc]
+ def __getitem__(self, key: str) -> t.Any:
+ try:
+ return super().__getitem__(key)
+ except KeyError as e:
+ if key not in request.form:
+ raise
+
+ raise DebugFilesKeyError(request, key).with_traceback(
+ e.__traceback__
+ ) from None
+
+ newcls.__name__ = oldcls.__name__
+ newcls.__module__ = oldcls.__module__
+ request.files.__class__ = newcls
+
+
+def _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]:
+ yield f"class: {type(loader).__module__}.{type(loader).__name__}"
+ for key, value in sorted(loader.__dict__.items()):
+ if key.startswith("_"):
+ continue
+ if isinstance(value, (tuple, list)):
+ if not all(isinstance(x, str) for x in value):
+ continue
+ yield f"{key}:"
+ for item in value:
+ yield f" - {item}"
+ continue
+ elif not isinstance(value, (str, int, float, bool)):
+ continue
+ yield f"{key}: {value!r}"
+
+
+def explain_template_loading_attempts(
+ app: App,
+ template: str,
+ attempts: list[
+ tuple[
+ BaseLoader,
+ Scaffold,
+ tuple[str, str | None, t.Callable[[], bool] | None] | None,
+ ]
+ ],
+) -> None:
+ """This should help developers understand what failed"""
+ info = [f"Locating template {template!r}:"]
+ total_found = 0
+ blueprint = None
+ if request_ctx and request_ctx.request.blueprint is not None:
+ blueprint = request_ctx.request.blueprint
+
+ for idx, (loader, srcobj, triple) in enumerate(attempts):
+ if isinstance(srcobj, App):
+ src_info = f"application {srcobj.import_name!r}"
+ elif isinstance(srcobj, Blueprint):
+ src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"
+ else:
+ src_info = repr(srcobj)
+
+ info.append(f"{idx + 1:5}: trying loader of {src_info}")
+
+ for line in _dump_loader_info(loader):
+ info.append(f" {line}")
+
+ if triple is None:
+ detail = "no match"
+ else:
+ detail = f"found ({triple[1] or ''!r})"
+ total_found += 1
+ info.append(f" -> {detail}")
+
+ seems_fishy = False
+ if total_found == 0:
+ info.append("Error: the template could not be found.")
+ seems_fishy = True
+ elif total_found > 1:
+ info.append("Warning: multiple loaders returned a match for the template.")
+ seems_fishy = True
+
+ if blueprint is not None and seems_fishy:
+ info.append(
+ " The template was looked up from an endpoint that belongs"
+ f" to the blueprint {blueprint!r}."
+ )
+ info.append(" Maybe you did not place a template in the right folder?")
+ info.append(" See https://flask.palletsprojects.com/blueprints/#templates")
+
+ app.logger.info("\n".join(info))
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/globals.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/globals.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2c410cc5b6bf7e5facc4e604fffd2c620adfd58
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/globals.py
@@ -0,0 +1,51 @@
+from __future__ import annotations
+
+import typing as t
+from contextvars import ContextVar
+
+from werkzeug.local import LocalProxy
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from .app import Flask
+ from .ctx import _AppCtxGlobals
+ from .ctx import AppContext
+ from .ctx import RequestContext
+ from .sessions import SessionMixin
+ from .wrappers import Request
+
+
+_no_app_msg = """\
+Working outside of application context.
+
+This typically means that you attempted to use functionality that needed
+the current application. To solve this, set up an application context
+with app.app_context(). See the documentation for more information.\
+"""
+_cv_app: ContextVar[AppContext] = ContextVar("flask.app_ctx")
+app_ctx: AppContext = LocalProxy( # type: ignore[assignment]
+ _cv_app, unbound_message=_no_app_msg
+)
+current_app: Flask = LocalProxy( # type: ignore[assignment]
+ _cv_app, "app", unbound_message=_no_app_msg
+)
+g: _AppCtxGlobals = LocalProxy( # type: ignore[assignment]
+ _cv_app, "g", unbound_message=_no_app_msg
+)
+
+_no_req_msg = """\
+Working outside of request context.
+
+This typically means that you attempted to use functionality that needed
+an active HTTP request. Consult the documentation on testing for
+information about how to avoid this problem.\
+"""
+_cv_request: ContextVar[RequestContext] = ContextVar("flask.request_ctx")
+request_ctx: RequestContext = LocalProxy( # type: ignore[assignment]
+ _cv_request, unbound_message=_no_req_msg
+)
+request: Request = LocalProxy( # type: ignore[assignment]
+ _cv_request, "request", unbound_message=_no_req_msg
+)
+session: SessionMixin = LocalProxy( # type: ignore[assignment]
+ _cv_request, "session", unbound_message=_no_req_msg
+)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/helpers.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..359a842af8b0dca0c2353cfba4e0669182759608
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/helpers.py
@@ -0,0 +1,621 @@
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+import typing as t
+from datetime import datetime
+from functools import lru_cache
+from functools import update_wrapper
+
+import werkzeug.utils
+from werkzeug.exceptions import abort as _wz_abort
+from werkzeug.utils import redirect as _wz_redirect
+from werkzeug.wrappers import Response as BaseResponse
+
+from .globals import _cv_request
+from .globals import current_app
+from .globals import request
+from .globals import request_ctx
+from .globals import session
+from .signals import message_flashed
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from .wrappers import Response
+
+
+def get_debug_flag() -> bool:
+ """Get whether debug mode should be enabled for the app, indicated by the
+ :envvar:`FLASK_DEBUG` environment variable. The default is ``False``.
+ """
+ val = os.environ.get("FLASK_DEBUG")
+ return bool(val and val.lower() not in {"0", "false", "no"})
+
+
+def get_load_dotenv(default: bool = True) -> bool:
+ """Get whether the user has disabled loading default dotenv files by
+ setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load
+ the files.
+
+ :param default: What to return if the env var isn't set.
+ """
+ val = os.environ.get("FLASK_SKIP_DOTENV")
+
+ if not val:
+ return default
+
+ return val.lower() in ("0", "false", "no")
+
+
+def stream_with_context(
+ generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]],
+) -> t.Iterator[t.AnyStr]:
+ """Request contexts disappear when the response is started on the server.
+ This is done for efficiency reasons and to make it less likely to encounter
+ memory leaks with badly written WSGI middlewares. The downside is that if
+ you are using streamed responses, the generator cannot access request bound
+ information any more.
+
+ This function however can help you keep the context around for longer::
+
+ from flask import stream_with_context, request, Response
+
+ @app.route('/stream')
+ def streamed_response():
+ @stream_with_context
+ def generate():
+ yield 'Hello '
+ yield request.args['name']
+ yield '!'
+ return Response(generate())
+
+ Alternatively it can also be used around a specific generator::
+
+ from flask import stream_with_context, request, Response
+
+ @app.route('/stream')
+ def streamed_response():
+ def generate():
+ yield 'Hello '
+ yield request.args['name']
+ yield '!'
+ return Response(stream_with_context(generate()))
+
+ .. versionadded:: 0.9
+ """
+ try:
+ gen = iter(generator_or_function) # type: ignore[arg-type]
+ except TypeError:
+
+ def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:
+ gen = generator_or_function(*args, **kwargs) # type: ignore[operator]
+ return stream_with_context(gen)
+
+ return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]
+
+ def generator() -> t.Iterator[t.AnyStr | None]:
+ ctx = _cv_request.get(None)
+ if ctx is None:
+ raise RuntimeError(
+ "'stream_with_context' can only be used when a request"
+ " context is active, such as in a view function."
+ )
+ with ctx:
+ # Dummy sentinel. Has to be inside the context block or we're
+ # not actually keeping the context around.
+ yield None
+
+ # The try/finally is here so that if someone passes a WSGI level
+ # iterator in we're still running the cleanup logic. Generators
+ # don't need that because they are closed on their destruction
+ # automatically.
+ try:
+ yield from gen
+ finally:
+ if hasattr(gen, "close"):
+ gen.close()
+
+ # The trick is to start the generator. Then the code execution runs until
+ # the first dummy None is yielded at which point the context was already
+ # pushed. This item is discarded. Then when the iteration continues the
+ # real generator is executed.
+ wrapped_g = generator()
+ next(wrapped_g)
+ return wrapped_g # type: ignore[return-value]
+
+
+def make_response(*args: t.Any) -> Response:
+ """Sometimes it is necessary to set additional headers in a view. Because
+ views do not have to return response objects but can return a value that
+ is converted into a response object by Flask itself, it becomes tricky to
+ add headers to it. This function can be called instead of using a return
+ and you will get a response object which you can use to attach headers.
+
+ If view looked like this and you want to add a new header::
+
+ def index():
+ return render_template('index.html', foo=42)
+
+ You can now do something like this::
+
+ def index():
+ response = make_response(render_template('index.html', foo=42))
+ response.headers['X-Parachutes'] = 'parachutes are cool'
+ return response
+
+ This function accepts the very same arguments you can return from a
+ view function. This for example creates a response with a 404 error
+ code::
+
+ response = make_response(render_template('not_found.html'), 404)
+
+ The other use case of this function is to force the return value of a
+ view function into a response which is helpful with view
+ decorators::
+
+ response = make_response(view_function())
+ response.headers['X-Parachutes'] = 'parachutes are cool'
+
+ Internally this function does the following things:
+
+ - if no arguments are passed, it creates a new response argument
+ - if one argument is passed, :meth:`flask.Flask.make_response`
+ is invoked with it.
+ - if more than one argument is passed, the arguments are passed
+ to the :meth:`flask.Flask.make_response` function as tuple.
+
+ .. versionadded:: 0.6
+ """
+ if not args:
+ return current_app.response_class()
+ if len(args) == 1:
+ args = args[0]
+ return current_app.make_response(args)
+
+
+def url_for(
+ endpoint: str,
+ *,
+ _anchor: str | None = None,
+ _method: str | None = None,
+ _scheme: str | None = None,
+ _external: bool | None = None,
+ **values: t.Any,
+) -> str:
+ """Generate a URL to the given endpoint with the given values.
+
+ This requires an active request or application context, and calls
+ :meth:`current_app.url_for() `. See that method
+ for full documentation.
+
+ :param endpoint: The endpoint name associated with the URL to
+ generate. If this starts with a ``.``, the current blueprint
+ name (if any) will be used.
+ :param _anchor: If given, append this as ``#anchor`` to the URL.
+ :param _method: If given, generate the URL associated with this
+ method for the endpoint.
+ :param _scheme: If given, the URL will have this scheme if it is
+ external.
+ :param _external: If given, prefer the URL to be internal (False) or
+ require it to be external (True). External URLs include the
+ scheme and domain. When not in an active request, URLs are
+ external by default.
+ :param values: Values to use for the variable parts of the URL rule.
+ Unknown keys are appended as query string arguments, like
+ ``?a=b&c=d``.
+
+ .. versionchanged:: 2.2
+ Calls ``current_app.url_for``, allowing an app to override the
+ behavior.
+
+ .. versionchanged:: 0.10
+ The ``_scheme`` parameter was added.
+
+ .. versionchanged:: 0.9
+ The ``_anchor`` and ``_method`` parameters were added.
+
+ .. versionchanged:: 0.9
+ Calls ``app.handle_url_build_error`` on build errors.
+ """
+ return current_app.url_for(
+ endpoint,
+ _anchor=_anchor,
+ _method=_method,
+ _scheme=_scheme,
+ _external=_external,
+ **values,
+ )
+
+
+def redirect(
+ location: str, code: int = 302, Response: type[BaseResponse] | None = None
+) -> BaseResponse:
+ """Create a redirect response object.
+
+ If :data:`~flask.current_app` is available, it will use its
+ :meth:`~flask.Flask.redirect` method, otherwise it will use
+ :func:`werkzeug.utils.redirect`.
+
+ :param location: The URL to redirect to.
+ :param code: The status code for the redirect.
+ :param Response: The response class to use. Not used when
+ ``current_app`` is active, which uses ``app.response_class``.
+
+ .. versionadded:: 2.2
+ Calls ``current_app.redirect`` if available instead of always
+ using Werkzeug's default ``redirect``.
+ """
+ if current_app:
+ return current_app.redirect(location, code=code)
+
+ return _wz_redirect(location, code=code, Response=Response)
+
+
+def abort(code: int | BaseResponse, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:
+ """Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given
+ status code.
+
+ If :data:`~flask.current_app` is available, it will call its
+ :attr:`~flask.Flask.aborter` object, otherwise it will use
+ :func:`werkzeug.exceptions.abort`.
+
+ :param code: The status code for the exception, which must be
+ registered in ``app.aborter``.
+ :param args: Passed to the exception.
+ :param kwargs: Passed to the exception.
+
+ .. versionadded:: 2.2
+ Calls ``current_app.aborter`` if available instead of always
+ using Werkzeug's default ``abort``.
+ """
+ if current_app:
+ current_app.aborter(code, *args, **kwargs)
+
+ _wz_abort(code, *args, **kwargs)
+
+
+def get_template_attribute(template_name: str, attribute: str) -> t.Any:
+ """Loads a macro (or variable) a template exports. This can be used to
+ invoke a macro from within Python code. If you for example have a
+ template named :file:`_cider.html` with the following contents:
+
+ .. sourcecode:: html+jinja
+
+ {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
+
+ You can access this from Python code like this::
+
+ hello = get_template_attribute('_cider.html', 'hello')
+ return hello('World')
+
+ .. versionadded:: 0.2
+
+ :param template_name: the name of the template
+ :param attribute: the name of the variable of macro to access
+ """
+ return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
+
+
+def flash(message: str, category: str = "message") -> None:
+ """Flashes a message to the next request. In order to remove the
+ flashed message from the session and to display it to the user,
+ the template has to call :func:`get_flashed_messages`.
+
+ .. versionchanged:: 0.3
+ `category` parameter added.
+
+ :param message: the message to be flashed.
+ :param category: the category for the message. The following values
+ are recommended: ``'message'`` for any kind of message,
+ ``'error'`` for errors, ``'info'`` for information
+ messages and ``'warning'`` for warnings. However any
+ kind of string can be used as category.
+ """
+ # Original implementation:
+ #
+ # session.setdefault('_flashes', []).append((category, message))
+ #
+ # This assumed that changes made to mutable structures in the session are
+ # always in sync with the session object, which is not true for session
+ # implementations that use external storage for keeping their keys/values.
+ flashes = session.get("_flashes", [])
+ flashes.append((category, message))
+ session["_flashes"] = flashes
+ app = current_app._get_current_object() # type: ignore
+ message_flashed.send(
+ app,
+ _async_wrapper=app.ensure_sync,
+ message=message,
+ category=category,
+ )
+
+
+def get_flashed_messages(
+ with_categories: bool = False, category_filter: t.Iterable[str] = ()
+) -> list[str] | list[tuple[str, str]]:
+ """Pulls all flashed messages from the session and returns them.
+ Further calls in the same request to the function will return
+ the same messages. By default just the messages are returned,
+ but when `with_categories` is set to ``True``, the return value will
+ be a list of tuples in the form ``(category, message)`` instead.
+
+ Filter the flashed messages to one or more categories by providing those
+ categories in `category_filter`. This allows rendering categories in
+ separate html blocks. The `with_categories` and `category_filter`
+ arguments are distinct:
+
+ * `with_categories` controls whether categories are returned with message
+ text (``True`` gives a tuple, where ``False`` gives just the message text).
+ * `category_filter` filters the messages down to only those matching the
+ provided categories.
+
+ See :doc:`/patterns/flashing` for examples.
+
+ .. versionchanged:: 0.3
+ `with_categories` parameter added.
+
+ .. versionchanged:: 0.9
+ `category_filter` parameter added.
+
+ :param with_categories: set to ``True`` to also receive categories.
+ :param category_filter: filter of categories to limit return values. Only
+ categories in the list will be returned.
+ """
+ flashes = request_ctx.flashes
+ if flashes is None:
+ flashes = session.pop("_flashes") if "_flashes" in session else []
+ request_ctx.flashes = flashes
+ if category_filter:
+ flashes = list(filter(lambda f: f[0] in category_filter, flashes))
+ if not with_categories:
+ return [x[1] for x in flashes]
+ return flashes
+
+
+def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]:
+ if kwargs.get("max_age") is None:
+ kwargs["max_age"] = current_app.get_send_file_max_age
+
+ kwargs.update(
+ environ=request.environ,
+ use_x_sendfile=current_app.config["USE_X_SENDFILE"],
+ response_class=current_app.response_class,
+ _root_path=current_app.root_path, # type: ignore
+ )
+ return kwargs
+
+
+def send_file(
+ path_or_file: os.PathLike[t.AnyStr] | str | t.BinaryIO,
+ mimetype: str | None = None,
+ as_attachment: bool = False,
+ download_name: str | None = None,
+ conditional: bool = True,
+ etag: bool | str = True,
+ last_modified: datetime | int | float | None = None,
+ max_age: None | (int | t.Callable[[str | None], int | None]) = None,
+) -> Response:
+ """Send the contents of a file to the client.
+
+ The first argument can be a file path or a file-like object. Paths
+ are preferred in most cases because Werkzeug can manage the file and
+ get extra information from the path. Passing a file-like object
+ requires that the file is opened in binary mode, and is mostly
+ useful when building a file in memory with :class:`io.BytesIO`.
+
+ Never pass file paths provided by a user. The path is assumed to be
+ trusted, so a user could craft a path to access a file you didn't
+ intend. Use :func:`send_from_directory` to safely serve
+ user-requested paths from within a directory.
+
+ If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
+ used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
+ if the HTTP server supports ``X-Sendfile``, configuring Flask with
+ ``USE_X_SENDFILE = True`` will tell the server to send the given
+ path, which is much more efficient than reading it in Python.
+
+ :param path_or_file: The path to the file to send, relative to the
+ current working directory if a relative path is given.
+ Alternatively, a file-like object opened in binary mode. Make
+ sure the file pointer is seeked to the start of the data.
+ :param mimetype: The MIME type to send for the file. If not
+ provided, it will try to detect it from the file name.
+ :param as_attachment: Indicate to a browser that it should offer to
+ save the file instead of displaying it.
+ :param download_name: The default name browsers will use when saving
+ the file. Defaults to the passed file name.
+ :param conditional: Enable conditional and range responses based on
+ request headers. Requires passing a file path and ``environ``.
+ :param etag: Calculate an ETag for the file, which requires passing
+ a file path. Can also be a string to use instead.
+ :param last_modified: The last modified time to send for the file,
+ in seconds. If not provided, it will try to detect it from the
+ file path.
+ :param max_age: How long the client should cache the file, in
+ seconds. If set, ``Cache-Control`` will be ``public``, otherwise
+ it will be ``no-cache`` to prefer conditional caching.
+
+ .. versionchanged:: 2.0
+ ``download_name`` replaces the ``attachment_filename``
+ parameter. If ``as_attachment=False``, it is passed with
+ ``Content-Disposition: inline`` instead.
+
+ .. versionchanged:: 2.0
+ ``max_age`` replaces the ``cache_timeout`` parameter.
+ ``conditional`` is enabled and ``max_age`` is not set by
+ default.
+
+ .. versionchanged:: 2.0
+ ``etag`` replaces the ``add_etags`` parameter. It can be a
+ string to use instead of generating one.
+
+ .. versionchanged:: 2.0
+ Passing a file-like object that inherits from
+ :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
+ than sending an empty file.
+
+ .. versionadded:: 2.0
+ Moved the implementation to Werkzeug. This is now a wrapper to
+ pass some Flask-specific arguments.
+
+ .. versionchanged:: 1.1
+ ``filename`` may be a :class:`~os.PathLike` object.
+
+ .. versionchanged:: 1.1
+ Passing a :class:`~io.BytesIO` object supports range requests.
+
+ .. versionchanged:: 1.0.3
+ Filenames are encoded with ASCII instead of Latin-1 for broader
+ compatibility with WSGI servers.
+
+ .. versionchanged:: 1.0
+ UTF-8 filenames as specified in :rfc:`2231` are supported.
+
+ .. versionchanged:: 0.12
+ The filename is no longer automatically inferred from file
+ objects. If you want to use automatic MIME and etag support,
+ pass a filename via ``filename_or_fp`` or
+ ``attachment_filename``.
+
+ .. versionchanged:: 0.12
+ ``attachment_filename`` is preferred over ``filename`` for MIME
+ detection.
+
+ .. versionchanged:: 0.9
+ ``cache_timeout`` defaults to
+ :meth:`Flask.get_send_file_max_age`.
+
+ .. versionchanged:: 0.7
+ MIME guessing and etag support for file-like objects was
+ removed because it was unreliable. Pass a filename if you are
+ able to, otherwise attach an etag yourself.
+
+ .. versionchanged:: 0.5
+ The ``add_etags``, ``cache_timeout`` and ``conditional``
+ parameters were added. The default behavior is to add etags.
+
+ .. versionadded:: 0.2
+ """
+ return werkzeug.utils.send_file( # type: ignore[return-value]
+ **_prepare_send_file_kwargs(
+ path_or_file=path_or_file,
+ environ=request.environ,
+ mimetype=mimetype,
+ as_attachment=as_attachment,
+ download_name=download_name,
+ conditional=conditional,
+ etag=etag,
+ last_modified=last_modified,
+ max_age=max_age,
+ )
+ )
+
+
+def send_from_directory(
+ directory: os.PathLike[str] | str,
+ path: os.PathLike[str] | str,
+ **kwargs: t.Any,
+) -> Response:
+ """Send a file from within a directory using :func:`send_file`.
+
+ .. code-block:: python
+
+ @app.route("/uploads/")
+ def download_file(name):
+ return send_from_directory(
+ app.config['UPLOAD_FOLDER'], name, as_attachment=True
+ )
+
+ This is a secure way to serve files from a folder, such as static
+ files or uploads. Uses :func:`~werkzeug.security.safe_join` to
+ ensure the path coming from the client is not maliciously crafted to
+ point outside the specified directory.
+
+ If the final path does not point to an existing regular file,
+ raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
+
+ :param directory: The directory that ``path`` must be located under,
+ relative to the current application's root path.
+ :param path: The path to the file to send, relative to
+ ``directory``.
+ :param kwargs: Arguments to pass to :func:`send_file`.
+
+ .. versionchanged:: 2.0
+ ``path`` replaces the ``filename`` parameter.
+
+ .. versionadded:: 2.0
+ Moved the implementation to Werkzeug. This is now a wrapper to
+ pass some Flask-specific arguments.
+
+ .. versionadded:: 0.5
+ """
+ return werkzeug.utils.send_from_directory( # type: ignore[return-value]
+ directory, path, **_prepare_send_file_kwargs(**kwargs)
+ )
+
+
+def get_root_path(import_name: str) -> str:
+ """Find the root path of a package, or the path that contains a
+ module. If it cannot be found, returns the current working
+ directory.
+
+ Not to be confused with the value returned by :func:`find_package`.
+
+ :meta private:
+ """
+ # Module already imported and has a file attribute. Use that first.
+ mod = sys.modules.get(import_name)
+
+ if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None:
+ return os.path.dirname(os.path.abspath(mod.__file__))
+
+ # Next attempt: check the loader.
+ try:
+ spec = importlib.util.find_spec(import_name)
+
+ if spec is None:
+ raise ValueError
+ except (ImportError, ValueError):
+ loader = None
+ else:
+ loader = spec.loader
+
+ # Loader does not exist or we're referring to an unloaded main
+ # module or a main module without path (interactive sessions), go
+ # with the current working directory.
+ if loader is None:
+ return os.getcwd()
+
+ if hasattr(loader, "get_filename"):
+ filepath = loader.get_filename(import_name)
+ else:
+ # Fall back to imports.
+ __import__(import_name)
+ mod = sys.modules[import_name]
+ filepath = getattr(mod, "__file__", None)
+
+ # If we don't have a file path it might be because it is a
+ # namespace package. In this case pick the root path from the
+ # first module that is contained in the package.
+ if filepath is None:
+ raise RuntimeError(
+ "No root path can be found for the provided module"
+ f" {import_name!r}. This can happen because the module"
+ " came from an import hook that does not provide file"
+ " name information or because it's a namespace package."
+ " In this case the root path needs to be explicitly"
+ " provided."
+ )
+
+ # filepath is import_name.py for a module, or __init__.py for a package.
+ return os.path.dirname(os.path.abspath(filepath)) # type: ignore[no-any-return]
+
+
+@lru_cache(maxsize=None)
+def _split_blueprint_path(name: str) -> list[str]:
+ out: list[str] = [name]
+
+ if "." in name:
+ out.extend(_split_blueprint_path(name.rpartition(".")[0]))
+
+ return out
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/logging.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cb8f43746c04b95b277d6dcb7af6d1930f09b62
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/logging.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+import logging
+import sys
+import typing as t
+
+from werkzeug.local import LocalProxy
+
+from .globals import request
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from .sansio.app import App
+
+
+@LocalProxy
+def wsgi_errors_stream() -> t.TextIO:
+ """Find the most appropriate error stream for the application. If a request
+ is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.
+
+ If you configure your own :class:`logging.StreamHandler`, you may want to
+ use this for the stream. If you are using file or dict configuration and
+ can't import this directly, you can refer to it as
+ ``ext://flask.logging.wsgi_errors_stream``.
+ """
+ if request:
+ return request.environ["wsgi.errors"] # type: ignore[no-any-return]
+
+ return sys.stderr
+
+
+def has_level_handler(logger: logging.Logger) -> bool:
+ """Check if there is a handler in the logging chain that will handle the
+ given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.
+ """
+ level = logger.getEffectiveLevel()
+ current = logger
+
+ while current:
+ if any(handler.level <= level for handler in current.handlers):
+ return True
+
+ if not current.propagate:
+ break
+
+ current = current.parent # type: ignore
+
+ return False
+
+
+#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format
+#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.
+default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore
+default_handler.setFormatter(
+ logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
+)
+
+
+def create_logger(app: App) -> logging.Logger:
+ """Get the Flask app's logger and configure it if needed.
+
+ The logger name will be the same as
+ :attr:`app.import_name `.
+
+ When :attr:`~flask.Flask.debug` is enabled, set the logger level to
+ :data:`logging.DEBUG` if it is not set.
+
+ If there is no handler for the logger's effective level, add a
+ :class:`~logging.StreamHandler` for
+ :func:`~flask.logging.wsgi_errors_stream` with a basic format.
+ """
+ logger = logging.getLogger(app.name)
+
+ if app.debug and not logger.level:
+ logger.setLevel(logging.DEBUG)
+
+ if not has_level_handler(logger):
+ logger.addHandler(default_handler)
+
+ return logger
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/py.typed b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/sessions.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/sessions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee19ad6387ff799e4300476aa4a1354426656364
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/sessions.py
@@ -0,0 +1,379 @@
+from __future__ import annotations
+
+import hashlib
+import typing as t
+from collections.abc import MutableMapping
+from datetime import datetime
+from datetime import timezone
+
+from itsdangerous import BadSignature
+from itsdangerous import URLSafeTimedSerializer
+from werkzeug.datastructures import CallbackDict
+
+from .json.tag import TaggedJSONSerializer
+
+if t.TYPE_CHECKING: # pragma: no cover
+ import typing_extensions as te
+
+ from .app import Flask
+ from .wrappers import Request
+ from .wrappers import Response
+
+
+# TODO generic when Python > 3.8
+class SessionMixin(MutableMapping): # type: ignore[type-arg]
+ """Expands a basic dictionary with session attributes."""
+
+ @property
+ def permanent(self) -> bool:
+ """This reflects the ``'_permanent'`` key in the dict."""
+ return self.get("_permanent", False)
+
+ @permanent.setter
+ def permanent(self, value: bool) -> None:
+ self["_permanent"] = bool(value)
+
+ #: Some implementations can detect whether a session is newly
+ #: created, but that is not guaranteed. Use with caution. The mixin
+ # default is hard-coded ``False``.
+ new = False
+
+ #: Some implementations can detect changes to the session and set
+ #: this when that happens. The mixin default is hard coded to
+ #: ``True``.
+ modified = True
+
+ #: Some implementations can detect when session data is read or
+ #: written and set this when that happens. The mixin default is hard
+ #: coded to ``True``.
+ accessed = True
+
+
+# TODO generic when Python > 3.8
+class SecureCookieSession(CallbackDict, SessionMixin): # type: ignore[type-arg]
+ """Base class for sessions based on signed cookies.
+
+ This session backend will set the :attr:`modified` and
+ :attr:`accessed` attributes. It cannot reliably track whether a
+ session is new (vs. empty), so :attr:`new` remains hard coded to
+ ``False``.
+ """
+
+ #: When data is changed, this is set to ``True``. Only the session
+ #: dictionary itself is tracked; if the session contains mutable
+ #: data (for example a nested dict) then this must be set to
+ #: ``True`` manually when modifying that data. The session cookie
+ #: will only be written to the response if this is ``True``.
+ modified = False
+
+ #: When data is read or written, this is set to ``True``. Used by
+ # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``
+ #: header, which allows caching proxies to cache different pages for
+ #: different users.
+ accessed = False
+
+ def __init__(self, initial: t.Any = None) -> None:
+ def on_update(self: te.Self) -> None:
+ self.modified = True
+ self.accessed = True
+
+ super().__init__(initial, on_update)
+
+ def __getitem__(self, key: str) -> t.Any:
+ self.accessed = True
+ return super().__getitem__(key)
+
+ def get(self, key: str, default: t.Any = None) -> t.Any:
+ self.accessed = True
+ return super().get(key, default)
+
+ def setdefault(self, key: str, default: t.Any = None) -> t.Any:
+ self.accessed = True
+ return super().setdefault(key, default)
+
+
+class NullSession(SecureCookieSession):
+ """Class used to generate nicer error messages if sessions are not
+ available. Will still allow read-only access to the empty session
+ but fail on setting.
+ """
+
+ def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:
+ raise RuntimeError(
+ "The session is unavailable because no secret "
+ "key was set. Set the secret_key on the "
+ "application to something unique and secret."
+ )
+
+ __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail # type: ignore # noqa: B950
+ del _fail
+
+
+class SessionInterface:
+ """The basic interface you have to implement in order to replace the
+ default session interface which uses werkzeug's securecookie
+ implementation. The only methods you have to implement are
+ :meth:`open_session` and :meth:`save_session`, the others have
+ useful defaults which you don't need to change.
+
+ The session object returned by the :meth:`open_session` method has to
+ provide a dictionary like interface plus the properties and methods
+ from the :class:`SessionMixin`. We recommend just subclassing a dict
+ and adding that mixin::
+
+ class Session(dict, SessionMixin):
+ pass
+
+ If :meth:`open_session` returns ``None`` Flask will call into
+ :meth:`make_null_session` to create a session that acts as replacement
+ if the session support cannot work because some requirement is not
+ fulfilled. The default :class:`NullSession` class that is created
+ will complain that the secret key was not set.
+
+ To replace the session interface on an application all you have to do
+ is to assign :attr:`flask.Flask.session_interface`::
+
+ app = Flask(__name__)
+ app.session_interface = MySessionInterface()
+
+ Multiple requests with the same session may be sent and handled
+ concurrently. When implementing a new session interface, consider
+ whether reads or writes to the backing store must be synchronized.
+ There is no guarantee on the order in which the session for each
+ request is opened or saved, it will occur in the order that requests
+ begin and end processing.
+
+ .. versionadded:: 0.8
+ """
+
+ #: :meth:`make_null_session` will look here for the class that should
+ #: be created when a null session is requested. Likewise the
+ #: :meth:`is_null_session` method will perform a typecheck against
+ #: this type.
+ null_session_class = NullSession
+
+ #: A flag that indicates if the session interface is pickle based.
+ #: This can be used by Flask extensions to make a decision in regards
+ #: to how to deal with the session object.
+ #:
+ #: .. versionadded:: 0.10
+ pickle_based = False
+
+ def make_null_session(self, app: Flask) -> NullSession:
+ """Creates a null session which acts as a replacement object if the
+ real session support could not be loaded due to a configuration
+ error. This mainly aids the user experience because the job of the
+ null session is to still support lookup without complaining but
+ modifications are answered with a helpful error message of what
+ failed.
+
+ This creates an instance of :attr:`null_session_class` by default.
+ """
+ return self.null_session_class()
+
+ def is_null_session(self, obj: object) -> bool:
+ """Checks if a given object is a null session. Null sessions are
+ not asked to be saved.
+
+ This checks if the object is an instance of :attr:`null_session_class`
+ by default.
+ """
+ return isinstance(obj, self.null_session_class)
+
+ def get_cookie_name(self, app: Flask) -> str:
+ """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``."""
+ return app.config["SESSION_COOKIE_NAME"] # type: ignore[no-any-return]
+
+ def get_cookie_domain(self, app: Flask) -> str | None:
+ """The value of the ``Domain`` parameter on the session cookie. If not set,
+ browsers will only send the cookie to the exact domain it was set from.
+ Otherwise, they will send it to any subdomain of the given value as well.
+
+ Uses the :data:`SESSION_COOKIE_DOMAIN` config.
+
+ .. versionchanged:: 2.3
+ Not set by default, does not fall back to ``SERVER_NAME``.
+ """
+ return app.config["SESSION_COOKIE_DOMAIN"] # type: ignore[no-any-return]
+
+ def get_cookie_path(self, app: Flask) -> str:
+ """Returns the path for which the cookie should be valid. The
+ default implementation uses the value from the ``SESSION_COOKIE_PATH``
+ config var if it's set, and falls back to ``APPLICATION_ROOT`` or
+ uses ``/`` if it's ``None``.
+ """
+ return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"] # type: ignore[no-any-return]
+
+ def get_cookie_httponly(self, app: Flask) -> bool:
+ """Returns True if the session cookie should be httponly. This
+ currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``
+ config var.
+ """
+ return app.config["SESSION_COOKIE_HTTPONLY"] # type: ignore[no-any-return]
+
+ def get_cookie_secure(self, app: Flask) -> bool:
+ """Returns True if the cookie should be secure. This currently
+ just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
+ """
+ return app.config["SESSION_COOKIE_SECURE"] # type: ignore[no-any-return]
+
+ def get_cookie_samesite(self, app: Flask) -> str | None:
+ """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the
+ ``SameSite`` attribute. This currently just returns the value of
+ the :data:`SESSION_COOKIE_SAMESITE` setting.
+ """
+ return app.config["SESSION_COOKIE_SAMESITE"] # type: ignore[no-any-return]
+
+ def get_expiration_time(self, app: Flask, session: SessionMixin) -> datetime | None:
+ """A helper method that returns an expiration date for the session
+ or ``None`` if the session is linked to the browser session. The
+ default implementation returns now + the permanent session
+ lifetime configured on the application.
+ """
+ if session.permanent:
+ return datetime.now(timezone.utc) + app.permanent_session_lifetime
+ return None
+
+ def should_set_cookie(self, app: Flask, session: SessionMixin) -> bool:
+ """Used by session backends to determine if a ``Set-Cookie`` header
+ should be set for this session cookie for this response. If the session
+ has been modified, the cookie is set. If the session is permanent and
+ the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is
+ always set.
+
+ This check is usually skipped if the session was deleted.
+
+ .. versionadded:: 0.11
+ """
+
+ return session.modified or (
+ session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]
+ )
+
+ def open_session(self, app: Flask, request: Request) -> SessionMixin | None:
+ """This is called at the beginning of each request, after
+ pushing the request context, before matching the URL.
+
+ This must return an object which implements a dictionary-like
+ interface as well as the :class:`SessionMixin` interface.
+
+ This will return ``None`` to indicate that loading failed in
+ some way that is not immediately an error. The request
+ context will fall back to using :meth:`make_null_session`
+ in this case.
+ """
+ raise NotImplementedError()
+
+ def save_session(
+ self, app: Flask, session: SessionMixin, response: Response
+ ) -> None:
+ """This is called at the end of each request, after generating
+ a response, before removing the request context. It is skipped
+ if :meth:`is_null_session` returns ``True``.
+ """
+ raise NotImplementedError()
+
+
+session_json_serializer = TaggedJSONSerializer()
+
+
+def _lazy_sha1(string: bytes = b"") -> t.Any:
+ """Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
+ SHA-1, in which case the import and use as a default would fail before the
+ developer can configure something else.
+ """
+ return hashlib.sha1(string)
+
+
+class SecureCookieSessionInterface(SessionInterface):
+ """The default session interface that stores sessions in signed cookies
+ through the :mod:`itsdangerous` module.
+ """
+
+ #: the salt that should be applied on top of the secret key for the
+ #: signing of cookie based sessions.
+ salt = "cookie-session"
+ #: the hash function to use for the signature. The default is sha1
+ digest_method = staticmethod(_lazy_sha1)
+ #: the name of the itsdangerous supported key derivation. The default
+ #: is hmac.
+ key_derivation = "hmac"
+ #: A python serializer for the payload. The default is a compact
+ #: JSON derived serializer with support for some extra Python types
+ #: such as datetime objects or tuples.
+ serializer = session_json_serializer
+ session_class = SecureCookieSession
+
+ def get_signing_serializer(self, app: Flask) -> URLSafeTimedSerializer | None:
+ if not app.secret_key:
+ return None
+ signer_kwargs = dict(
+ key_derivation=self.key_derivation, digest_method=self.digest_method
+ )
+ return URLSafeTimedSerializer(
+ app.secret_key,
+ salt=self.salt,
+ serializer=self.serializer,
+ signer_kwargs=signer_kwargs,
+ )
+
+ def open_session(self, app: Flask, request: Request) -> SecureCookieSession | None:
+ s = self.get_signing_serializer(app)
+ if s is None:
+ return None
+ val = request.cookies.get(self.get_cookie_name(app))
+ if not val:
+ return self.session_class()
+ max_age = int(app.permanent_session_lifetime.total_seconds())
+ try:
+ data = s.loads(val, max_age=max_age)
+ return self.session_class(data)
+ except BadSignature:
+ return self.session_class()
+
+ def save_session(
+ self, app: Flask, session: SessionMixin, response: Response
+ ) -> None:
+ name = self.get_cookie_name(app)
+ domain = self.get_cookie_domain(app)
+ path = self.get_cookie_path(app)
+ secure = self.get_cookie_secure(app)
+ samesite = self.get_cookie_samesite(app)
+ httponly = self.get_cookie_httponly(app)
+
+ # Add a "Vary: Cookie" header if the session was accessed at all.
+ if session.accessed:
+ response.vary.add("Cookie")
+
+ # If the session is modified to be empty, remove the cookie.
+ # If the session is empty, return without setting the cookie.
+ if not session:
+ if session.modified:
+ response.delete_cookie(
+ name,
+ domain=domain,
+ path=path,
+ secure=secure,
+ samesite=samesite,
+ httponly=httponly,
+ )
+ response.vary.add("Cookie")
+
+ return
+
+ if not self.should_set_cookie(app, session):
+ return
+
+ expires = self.get_expiration_time(app, session)
+ val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore
+ response.set_cookie(
+ name,
+ val, # type: ignore
+ expires=expires,
+ httponly=httponly,
+ domain=domain,
+ path=path,
+ secure=secure,
+ samesite=samesite,
+ )
+ response.vary.add("Cookie")
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/signals.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/signals.py
new file mode 100644
index 0000000000000000000000000000000000000000..444fda9987b0e77d78afdd08d74d31b5516c8642
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/signals.py
@@ -0,0 +1,17 @@
+from __future__ import annotations
+
+from blinker import Namespace
+
+# This namespace is only for signals provided by Flask itself.
+_signals = Namespace()
+
+template_rendered = _signals.signal("template-rendered")
+before_render_template = _signals.signal("before-render-template")
+request_started = _signals.signal("request-started")
+request_finished = _signals.signal("request-finished")
+request_tearing_down = _signals.signal("request-tearing-down")
+got_request_exception = _signals.signal("got-request-exception")
+appcontext_tearing_down = _signals.signal("appcontext-tearing-down")
+appcontext_pushed = _signals.signal("appcontext-pushed")
+appcontext_popped = _signals.signal("appcontext-popped")
+message_flashed = _signals.signal("message-flashed")
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/templating.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/templating.py
new file mode 100644
index 0000000000000000000000000000000000000000..618a3b35d04520357ff659a15f7587fbdabf3b60
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/templating.py
@@ -0,0 +1,219 @@
+from __future__ import annotations
+
+import typing as t
+
+from jinja2 import BaseLoader
+from jinja2 import Environment as BaseEnvironment
+from jinja2 import Template
+from jinja2 import TemplateNotFound
+
+from .globals import _cv_app
+from .globals import _cv_request
+from .globals import current_app
+from .globals import request
+from .helpers import stream_with_context
+from .signals import before_render_template
+from .signals import template_rendered
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from .app import Flask
+ from .sansio.app import App
+ from .sansio.scaffold import Scaffold
+
+
+def _default_template_ctx_processor() -> dict[str, t.Any]:
+ """Default template context processor. Injects `request`,
+ `session` and `g`.
+ """
+ appctx = _cv_app.get(None)
+ reqctx = _cv_request.get(None)
+ rv: dict[str, t.Any] = {}
+ if appctx is not None:
+ rv["g"] = appctx.g
+ if reqctx is not None:
+ rv["request"] = reqctx.request
+ rv["session"] = reqctx.session
+ return rv
+
+
+class Environment(BaseEnvironment):
+ """Works like a regular Jinja2 environment but has some additional
+ knowledge of how Flask's blueprint works so that it can prepend the
+ name of the blueprint to referenced templates if necessary.
+ """
+
+ def __init__(self, app: App, **options: t.Any) -> None:
+ if "loader" not in options:
+ options["loader"] = app.create_global_jinja_loader()
+ BaseEnvironment.__init__(self, **options)
+ self.app = app
+
+
+class DispatchingJinjaLoader(BaseLoader):
+ """A loader that looks for templates in the application and all
+ the blueprint folders.
+ """
+
+ def __init__(self, app: App) -> None:
+ self.app = app
+
+ def get_source(
+ self, environment: BaseEnvironment, template: str
+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:
+ if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:
+ return self._get_source_explained(environment, template)
+ return self._get_source_fast(environment, template)
+
+ def _get_source_explained(
+ self, environment: BaseEnvironment, template: str
+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:
+ attempts = []
+ rv: tuple[str, str | None, t.Callable[[], bool] | None] | None
+ trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None
+
+ for srcobj, loader in self._iter_loaders(template):
+ try:
+ rv = loader.get_source(environment, template)
+ if trv is None:
+ trv = rv
+ except TemplateNotFound:
+ rv = None
+ attempts.append((loader, srcobj, rv))
+
+ from .debughelpers import explain_template_loading_attempts
+
+ explain_template_loading_attempts(self.app, template, attempts)
+
+ if trv is not None:
+ return trv
+ raise TemplateNotFound(template)
+
+ def _get_source_fast(
+ self, environment: BaseEnvironment, template: str
+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:
+ for _srcobj, loader in self._iter_loaders(template):
+ try:
+ return loader.get_source(environment, template)
+ except TemplateNotFound:
+ continue
+ raise TemplateNotFound(template)
+
+ def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:
+ loader = self.app.jinja_loader
+ if loader is not None:
+ yield self.app, loader
+
+ for blueprint in self.app.iter_blueprints():
+ loader = blueprint.jinja_loader
+ if loader is not None:
+ yield blueprint, loader
+
+ def list_templates(self) -> list[str]:
+ result = set()
+ loader = self.app.jinja_loader
+ if loader is not None:
+ result.update(loader.list_templates())
+
+ for blueprint in self.app.iter_blueprints():
+ loader = blueprint.jinja_loader
+ if loader is not None:
+ for template in loader.list_templates():
+ result.add(template)
+
+ return list(result)
+
+
+def _render(app: Flask, template: Template, context: dict[str, t.Any]) -> str:
+ app.update_template_context(context)
+ before_render_template.send(
+ app, _async_wrapper=app.ensure_sync, template=template, context=context
+ )
+ rv = template.render(context)
+ template_rendered.send(
+ app, _async_wrapper=app.ensure_sync, template=template, context=context
+ )
+ return rv
+
+
+def render_template(
+ template_name_or_list: str | Template | list[str | Template],
+ **context: t.Any,
+) -> str:
+ """Render a template by name with the given context.
+
+ :param template_name_or_list: The name of the template to render. If
+ a list is given, the first name to exist will be rendered.
+ :param context: The variables to make available in the template.
+ """
+ app = current_app._get_current_object() # type: ignore[attr-defined]
+ template = app.jinja_env.get_or_select_template(template_name_or_list)
+ return _render(app, template, context)
+
+
+def render_template_string(source: str, **context: t.Any) -> str:
+ """Render a template from the given source string with the given
+ context.
+
+ :param source: The source code of the template to render.
+ :param context: The variables to make available in the template.
+ """
+ app = current_app._get_current_object() # type: ignore[attr-defined]
+ template = app.jinja_env.from_string(source)
+ return _render(app, template, context)
+
+
+def _stream(
+ app: Flask, template: Template, context: dict[str, t.Any]
+) -> t.Iterator[str]:
+ app.update_template_context(context)
+ before_render_template.send(
+ app, _async_wrapper=app.ensure_sync, template=template, context=context
+ )
+
+ def generate() -> t.Iterator[str]:
+ yield from template.generate(context)
+ template_rendered.send(
+ app, _async_wrapper=app.ensure_sync, template=template, context=context
+ )
+
+ rv = generate()
+
+ # If a request context is active, keep it while generating.
+ if request:
+ rv = stream_with_context(rv)
+
+ return rv
+
+
+def stream_template(
+ template_name_or_list: str | Template | list[str | Template],
+ **context: t.Any,
+) -> t.Iterator[str]:
+ """Render a template by name with the given context as a stream.
+ This returns an iterator of strings, which can be used as a
+ streaming response from a view.
+
+ :param template_name_or_list: The name of the template to render. If
+ a list is given, the first name to exist will be rendered.
+ :param context: The variables to make available in the template.
+
+ .. versionadded:: 2.2
+ """
+ app = current_app._get_current_object() # type: ignore[attr-defined]
+ template = app.jinja_env.get_or_select_template(template_name_or_list)
+ return _stream(app, template, context)
+
+
+def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:
+ """Render a template from the given source string with the given
+ context as a stream. This returns an iterator of strings, which can
+ be used as a streaming response from a view.
+
+ :param source: The source code of the template to render.
+ :param context: The variables to make available in the template.
+
+ .. versionadded:: 2.2
+ """
+ app = current_app._get_current_object() # type: ignore[attr-defined]
+ template = app.jinja_env.from_string(source)
+ return _stream(app, template, context)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/testing.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..a27b7c8fe9ef6707580d4de2247809aa4bf59276
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/testing.py
@@ -0,0 +1,298 @@
+from __future__ import annotations
+
+import importlib.metadata
+import typing as t
+from contextlib import contextmanager
+from contextlib import ExitStack
+from copy import copy
+from types import TracebackType
+from urllib.parse import urlsplit
+
+import werkzeug.test
+from click.testing import CliRunner
+from werkzeug.test import Client
+from werkzeug.wrappers import Request as BaseRequest
+
+from .cli import ScriptInfo
+from .sessions import SessionMixin
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from _typeshed.wsgi import WSGIEnvironment
+ from werkzeug.test import TestResponse
+
+ from .app import Flask
+
+
+class EnvironBuilder(werkzeug.test.EnvironBuilder):
+ """An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the
+ application.
+
+ :param app: The Flask application to configure the environment from.
+ :param path: URL path being requested.
+ :param base_url: Base URL where the app is being served, which
+ ``path`` is relative to. If not given, built from
+ :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
+ :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
+ :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.
+ :param url_scheme: Scheme to use instead of
+ :data:`PREFERRED_URL_SCHEME`.
+ :param json: If given, this is serialized as JSON and passed as
+ ``data``. Also defaults ``content_type`` to
+ ``application/json``.
+ :param args: other positional arguments passed to
+ :class:`~werkzeug.test.EnvironBuilder`.
+ :param kwargs: other keyword arguments passed to
+ :class:`~werkzeug.test.EnvironBuilder`.
+ """
+
+ def __init__(
+ self,
+ app: Flask,
+ path: str = "/",
+ base_url: str | None = None,
+ subdomain: str | None = None,
+ url_scheme: str | None = None,
+ *args: t.Any,
+ **kwargs: t.Any,
+ ) -> None:
+ assert not (base_url or subdomain or url_scheme) or (
+ base_url is not None
+ ) != bool(
+ subdomain or url_scheme
+ ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'
+
+ if base_url is None:
+ http_host = app.config.get("SERVER_NAME") or "localhost"
+ app_root = app.config["APPLICATION_ROOT"]
+
+ if subdomain:
+ http_host = f"{subdomain}.{http_host}"
+
+ if url_scheme is None:
+ url_scheme = app.config["PREFERRED_URL_SCHEME"]
+
+ url = urlsplit(path)
+ base_url = (
+ f"{url.scheme or url_scheme}://{url.netloc or http_host}"
+ f"/{app_root.lstrip('/')}"
+ )
+ path = url.path
+
+ if url.query:
+ sep = b"?" if isinstance(url.query, bytes) else "?"
+ path += sep + url.query
+
+ self.app = app
+ super().__init__(path, base_url, *args, **kwargs)
+
+ def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str: # type: ignore
+ """Serialize ``obj`` to a JSON-formatted string.
+
+ The serialization will be configured according to the config associated
+ with this EnvironBuilder's ``app``.
+ """
+ return self.app.json.dumps(obj, **kwargs)
+
+
+_werkzeug_version = ""
+
+
+def _get_werkzeug_version() -> str:
+ global _werkzeug_version
+
+ if not _werkzeug_version:
+ _werkzeug_version = importlib.metadata.version("werkzeug")
+
+ return _werkzeug_version
+
+
+class FlaskClient(Client):
+ """Works like a regular Werkzeug test client but has knowledge about
+ Flask's contexts to defer the cleanup of the request context until
+ the end of a ``with`` block. For general information about how to
+ use this class refer to :class:`werkzeug.test.Client`.
+
+ .. versionchanged:: 0.12
+ `app.test_client()` includes preset default environment, which can be
+ set after instantiation of the `app.test_client()` object in
+ `client.environ_base`.
+
+ Basic usage is outlined in the :doc:`/testing` chapter.
+ """
+
+ application: Flask
+
+ def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
+ super().__init__(*args, **kwargs)
+ self.preserve_context = False
+ self._new_contexts: list[t.ContextManager[t.Any]] = []
+ self._context_stack = ExitStack()
+ self.environ_base = {
+ "REMOTE_ADDR": "127.0.0.1",
+ "HTTP_USER_AGENT": f"Werkzeug/{_get_werkzeug_version()}",
+ }
+
+ @contextmanager
+ def session_transaction(
+ self, *args: t.Any, **kwargs: t.Any
+ ) -> t.Iterator[SessionMixin]:
+ """When used in combination with a ``with`` statement this opens a
+ session transaction. This can be used to modify the session that
+ the test client uses. Once the ``with`` block is left the session is
+ stored back.
+
+ ::
+
+ with client.session_transaction() as session:
+ session['value'] = 42
+
+ Internally this is implemented by going through a temporary test
+ request context and since session handling could depend on
+ request variables this function accepts the same arguments as
+ :meth:`~flask.Flask.test_request_context` which are directly
+ passed through.
+ """
+ if self._cookies is None:
+ raise TypeError(
+ "Cookies are disabled. Create a client with 'use_cookies=True'."
+ )
+
+ app = self.application
+ ctx = app.test_request_context(*args, **kwargs)
+ self._add_cookies_to_wsgi(ctx.request.environ)
+
+ with ctx:
+ sess = app.session_interface.open_session(app, ctx.request)
+
+ if sess is None:
+ raise RuntimeError("Session backend did not open a session.")
+
+ yield sess
+ resp = app.response_class()
+
+ if app.session_interface.is_null_session(sess):
+ return
+
+ with ctx:
+ app.session_interface.save_session(app, sess, resp)
+
+ self._update_cookies_from_response(
+ ctx.request.host.partition(":")[0],
+ ctx.request.path,
+ resp.headers.getlist("Set-Cookie"),
+ )
+
+ def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:
+ out = {**self.environ_base, **other}
+
+ if self.preserve_context:
+ out["werkzeug.debug.preserve_context"] = self._new_contexts.append
+
+ return out
+
+ def _request_from_builder_args(
+ self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]
+ ) -> BaseRequest:
+ kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {}))
+ builder = EnvironBuilder(self.application, *args, **kwargs)
+
+ try:
+ return builder.get_request()
+ finally:
+ builder.close()
+
+ def open(
+ self,
+ *args: t.Any,
+ buffered: bool = False,
+ follow_redirects: bool = False,
+ **kwargs: t.Any,
+ ) -> TestResponse:
+ if args and isinstance(
+ args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)
+ ):
+ if isinstance(args[0], werkzeug.test.EnvironBuilder):
+ builder = copy(args[0])
+ builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type]
+ request = builder.get_request()
+ elif isinstance(args[0], dict):
+ request = EnvironBuilder.from_environ(
+ args[0], app=self.application, environ_base=self._copy_environ({})
+ ).get_request()
+ else:
+ # isinstance(args[0], BaseRequest)
+ request = copy(args[0])
+ request.environ = self._copy_environ(request.environ)
+ else:
+ # request is None
+ request = self._request_from_builder_args(args, kwargs)
+
+ # Pop any previously preserved contexts. This prevents contexts
+ # from being preserved across redirects or multiple requests
+ # within a single block.
+ self._context_stack.close()
+
+ response = super().open(
+ request,
+ buffered=buffered,
+ follow_redirects=follow_redirects,
+ )
+ response.json_module = self.application.json # type: ignore[assignment]
+
+ # Re-push contexts that were preserved during the request.
+ while self._new_contexts:
+ cm = self._new_contexts.pop()
+ self._context_stack.enter_context(cm)
+
+ return response
+
+ def __enter__(self) -> FlaskClient:
+ if self.preserve_context:
+ raise RuntimeError("Cannot nest client invocations")
+ self.preserve_context = True
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type | None,
+ exc_value: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ self.preserve_context = False
+ self._context_stack.close()
+
+
+class FlaskCliRunner(CliRunner):
+ """A :class:`~click.testing.CliRunner` for testing a Flask app's
+ CLI commands. Typically created using
+ :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.
+ """
+
+ def __init__(self, app: Flask, **kwargs: t.Any) -> None:
+ self.app = app
+ super().__init__(**kwargs)
+
+ def invoke( # type: ignore
+ self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any
+ ) -> t.Any:
+ """Invokes a CLI command in an isolated environment. See
+ :meth:`CliRunner.invoke ` for
+ full method documentation. See :ref:`testing-cli` for examples.
+
+ If the ``obj`` argument is not given, passes an instance of
+ :class:`~flask.cli.ScriptInfo` that knows how to load the Flask
+ app being tested.
+
+ :param cli: Command object to invoke. Default is the app's
+ :attr:`~flask.app.Flask.cli` group.
+ :param args: List of strings to invoke the command with.
+
+ :return: a :class:`~click.testing.Result` object.
+ """
+ if cli is None:
+ cli = self.app.cli
+
+ if "obj" not in kwargs:
+ kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)
+
+ return super().invoke(cli, args, **kwargs)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/typing.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf6d4ae6dd775a8d6931e46a8a446a795094078b
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/typing.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+import typing as t
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from _typeshed.wsgi import WSGIApplication # noqa: F401
+ from werkzeug.datastructures import Headers # noqa: F401
+ from werkzeug.sansio.response import Response # noqa: F401
+
+# The possible types that are directly convertible or are a Response object.
+ResponseValue = t.Union[
+ "Response",
+ str,
+ bytes,
+ t.List[t.Any],
+ # Only dict is actually accepted, but Mapping allows for TypedDict.
+ t.Mapping[str, t.Any],
+ t.Iterator[str],
+ t.Iterator[bytes],
+]
+
+# the possible types for an individual HTTP header
+# This should be a Union, but mypy doesn't pass unless it's a TypeVar.
+HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]
+
+# the possible types for HTTP headers
+HeadersValue = t.Union[
+ "Headers",
+ t.Mapping[str, HeaderValue],
+ t.Sequence[t.Tuple[str, HeaderValue]],
+]
+
+# The possible types returned by a route function.
+ResponseReturnValue = t.Union[
+ ResponseValue,
+ t.Tuple[ResponseValue, HeadersValue],
+ t.Tuple[ResponseValue, int],
+ t.Tuple[ResponseValue, int, HeadersValue],
+ "WSGIApplication",
+]
+
+# Allow any subclass of werkzeug.Response, such as the one from Flask,
+# as a callback argument. Using werkzeug.Response directly makes a
+# callback annotated with flask.Response fail type checking.
+ResponseClass = t.TypeVar("ResponseClass", bound="Response")
+
+AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named
+AfterRequestCallable = t.Union[
+ t.Callable[[ResponseClass], ResponseClass],
+ t.Callable[[ResponseClass], t.Awaitable[ResponseClass]],
+]
+BeforeFirstRequestCallable = t.Union[
+ t.Callable[[], None], t.Callable[[], t.Awaitable[None]]
+]
+BeforeRequestCallable = t.Union[
+ t.Callable[[], t.Optional[ResponseReturnValue]],
+ t.Callable[[], t.Awaitable[t.Optional[ResponseReturnValue]]],
+]
+ShellContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]
+TeardownCallable = t.Union[
+ t.Callable[[t.Optional[BaseException]], None],
+ t.Callable[[t.Optional[BaseException]], t.Awaitable[None]],
+]
+TemplateContextProcessorCallable = t.Union[
+ t.Callable[[], t.Dict[str, t.Any]],
+ t.Callable[[], t.Awaitable[t.Dict[str, t.Any]]],
+]
+TemplateFilterCallable = t.Callable[..., t.Any]
+TemplateGlobalCallable = t.Callable[..., t.Any]
+TemplateTestCallable = t.Callable[..., bool]
+URLDefaultCallable = t.Callable[[str, t.Dict[str, t.Any]], None]
+URLValuePreprocessorCallable = t.Callable[
+ [t.Optional[str], t.Optional[t.Dict[str, t.Any]]], None
+]
+
+# This should take Exception, but that either breaks typing the argument
+# with a specific exception, or decorating multiple times with different
+# exceptions (and using a union type on the argument).
+# https://github.com/pallets/flask/issues/4095
+# https://github.com/pallets/flask/issues/4295
+# https://github.com/pallets/flask/issues/4297
+ErrorHandlerCallable = t.Union[
+ t.Callable[[t.Any], ResponseReturnValue],
+ t.Callable[[t.Any], t.Awaitable[ResponseReturnValue]],
+]
+
+RouteCallable = t.Union[
+ t.Callable[..., ResponseReturnValue],
+ t.Callable[..., t.Awaitable[ResponseReturnValue]],
+]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/views.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/views.py
new file mode 100644
index 0000000000000000000000000000000000000000..794fdc06cf004f8589f288c346faca3f75c31c5b
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/views.py
@@ -0,0 +1,191 @@
+from __future__ import annotations
+
+import typing as t
+
+from . import typing as ft
+from .globals import current_app
+from .globals import request
+
+F = t.TypeVar("F", bound=t.Callable[..., t.Any])
+
+http_method_funcs = frozenset(
+ ["get", "post", "head", "options", "delete", "put", "trace", "patch"]
+)
+
+
+class View:
+ """Subclass this class and override :meth:`dispatch_request` to
+ create a generic class-based view. Call :meth:`as_view` to create a
+ view function that creates an instance of the class with the given
+ arguments and calls its ``dispatch_request`` method with any URL
+ variables.
+
+ See :doc:`views` for a detailed guide.
+
+ .. code-block:: python
+
+ class Hello(View):
+ init_every_request = False
+
+ def dispatch_request(self, name):
+ return f"Hello, {name}!"
+
+ app.add_url_rule(
+ "/hello/", view_func=Hello.as_view("hello")
+ )
+
+ Set :attr:`methods` on the class to change what methods the view
+ accepts.
+
+ Set :attr:`decorators` on the class to apply a list of decorators to
+ the generated view function. Decorators applied to the class itself
+ will not be applied to the generated view function!
+
+ Set :attr:`init_every_request` to ``False`` for efficiency, unless
+ you need to store request-global data on ``self``.
+ """
+
+ #: The methods this view is registered for. Uses the same default
+ #: (``["GET", "HEAD", "OPTIONS"]``) as ``route`` and
+ #: ``add_url_rule`` by default.
+ methods: t.ClassVar[t.Collection[str] | None] = None
+
+ #: Control whether the ``OPTIONS`` method is handled automatically.
+ #: Uses the same default (``True``) as ``route`` and
+ #: ``add_url_rule`` by default.
+ provide_automatic_options: t.ClassVar[bool | None] = None
+
+ #: A list of decorators to apply, in order, to the generated view
+ #: function. Remember that ``@decorator`` syntax is applied bottom
+ #: to top, so the first decorator in the list would be the bottom
+ #: decorator.
+ #:
+ #: .. versionadded:: 0.8
+ decorators: t.ClassVar[list[t.Callable[[F], F]]] = []
+
+ #: Create a new instance of this view class for every request by
+ #: default. If a view subclass sets this to ``False``, the same
+ #: instance is used for every request.
+ #:
+ #: A single instance is more efficient, especially if complex setup
+ #: is done during init. However, storing data on ``self`` is no
+ #: longer safe across requests, and :data:`~flask.g` should be used
+ #: instead.
+ #:
+ #: .. versionadded:: 2.2
+ init_every_request: t.ClassVar[bool] = True
+
+ def dispatch_request(self) -> ft.ResponseReturnValue:
+ """The actual view function behavior. Subclasses must override
+ this and return a valid response. Any variables from the URL
+ rule are passed as keyword arguments.
+ """
+ raise NotImplementedError()
+
+ @classmethod
+ def as_view(
+ cls, name: str, *class_args: t.Any, **class_kwargs: t.Any
+ ) -> ft.RouteCallable:
+ """Convert the class into a view function that can be registered
+ for a route.
+
+ By default, the generated view will create a new instance of the
+ view class for every request and call its
+ :meth:`dispatch_request` method. If the view class sets
+ :attr:`init_every_request` to ``False``, the same instance will
+ be used for every request.
+
+ Except for ``name``, all other arguments passed to this method
+ are forwarded to the view class ``__init__`` method.
+
+ .. versionchanged:: 2.2
+ Added the ``init_every_request`` class attribute.
+ """
+ if cls.init_every_request:
+
+ def view(**kwargs: t.Any) -> ft.ResponseReturnValue:
+ self = view.view_class( # type: ignore[attr-defined]
+ *class_args, **class_kwargs
+ )
+ return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]
+
+ else:
+ self = cls(*class_args, **class_kwargs)
+
+ def view(**kwargs: t.Any) -> ft.ResponseReturnValue:
+ return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]
+
+ if cls.decorators:
+ view.__name__ = name
+ view.__module__ = cls.__module__
+ for decorator in cls.decorators:
+ view = decorator(view)
+
+ # We attach the view class to the view function for two reasons:
+ # first of all it allows us to easily figure out what class-based
+ # view this thing came from, secondly it's also used for instantiating
+ # the view class so you can actually replace it with something else
+ # for testing purposes and debugging.
+ view.view_class = cls # type: ignore
+ view.__name__ = name
+ view.__doc__ = cls.__doc__
+ view.__module__ = cls.__module__
+ view.methods = cls.methods # type: ignore
+ view.provide_automatic_options = cls.provide_automatic_options # type: ignore
+ return view
+
+
+class MethodView(View):
+ """Dispatches request methods to the corresponding instance methods.
+ For example, if you implement a ``get`` method, it will be used to
+ handle ``GET`` requests.
+
+ This can be useful for defining a REST API.
+
+ :attr:`methods` is automatically set based on the methods defined on
+ the class.
+
+ See :doc:`views` for a detailed guide.
+
+ .. code-block:: python
+
+ class CounterAPI(MethodView):
+ def get(self):
+ return str(session.get("counter", 0))
+
+ def post(self):
+ session["counter"] = session.get("counter", 0) + 1
+ return redirect(url_for("counter"))
+
+ app.add_url_rule(
+ "/counter", view_func=CounterAPI.as_view("counter")
+ )
+ """
+
+ def __init_subclass__(cls, **kwargs: t.Any) -> None:
+ super().__init_subclass__(**kwargs)
+
+ if "methods" not in cls.__dict__:
+ methods = set()
+
+ for base in cls.__bases__:
+ if getattr(base, "methods", None):
+ methods.update(base.methods) # type: ignore[attr-defined]
+
+ for key in http_method_funcs:
+ if hasattr(cls, key):
+ methods.add(key.upper())
+
+ if methods:
+ cls.methods = methods
+
+ def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:
+ meth = getattr(self, request.method.lower(), None)
+
+ # If the request method is HEAD and we don't have a handler for it
+ # retry with GET.
+ if meth is None and request.method == "HEAD":
+ meth = getattr(self, "get", None)
+
+ assert meth is not None, f"Unimplemented method {request.method!r}"
+ return current_app.ensure_sync(meth)(**kwargs) # type: ignore[no-any-return]
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask/wrappers.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/wrappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1eca80783e132e063498aab62d9ca650fc2026f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask/wrappers.py
@@ -0,0 +1,174 @@
+from __future__ import annotations
+
+import typing as t
+
+from werkzeug.exceptions import BadRequest
+from werkzeug.exceptions import HTTPException
+from werkzeug.wrappers import Request as RequestBase
+from werkzeug.wrappers import Response as ResponseBase
+
+from . import json
+from .globals import current_app
+from .helpers import _split_blueprint_path
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from werkzeug.routing import Rule
+
+
+class Request(RequestBase):
+ """The request object used by default in Flask. Remembers the
+ matched endpoint and view arguments.
+
+ It is what ends up as :class:`~flask.request`. If you want to replace
+ the request object used you can subclass this and set
+ :attr:`~flask.Flask.request_class` to your subclass.
+
+ The request object is a :class:`~werkzeug.wrappers.Request` subclass and
+ provides all of the attributes Werkzeug defines plus a few Flask
+ specific ones.
+ """
+
+ json_module: t.Any = json
+
+ #: The internal URL rule that matched the request. This can be
+ #: useful to inspect which methods are allowed for the URL from
+ #: a before/after handler (``request.url_rule.methods``) etc.
+ #: Though if the request's method was invalid for the URL rule,
+ #: the valid list is available in ``routing_exception.valid_methods``
+ #: instead (an attribute of the Werkzeug exception
+ #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)
+ #: because the request was never internally bound.
+ #:
+ #: .. versionadded:: 0.6
+ url_rule: Rule | None = None
+
+ #: A dict of view arguments that matched the request. If an exception
+ #: happened when matching, this will be ``None``.
+ view_args: dict[str, t.Any] | None = None
+
+ #: If matching the URL failed, this is the exception that will be
+ #: raised / was raised as part of the request handling. This is
+ #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or
+ #: something similar.
+ routing_exception: HTTPException | None = None
+
+ @property
+ def max_content_length(self) -> int | None: # type: ignore[override]
+ """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""
+ if current_app:
+ return current_app.config["MAX_CONTENT_LENGTH"] # type: ignore[no-any-return]
+ else:
+ return None
+
+ @property
+ def endpoint(self) -> str | None:
+ """The endpoint that matched the request URL.
+
+ This will be ``None`` if matching failed or has not been
+ performed yet.
+
+ This in combination with :attr:`view_args` can be used to
+ reconstruct the same URL or a modified URL.
+ """
+ if self.url_rule is not None:
+ return self.url_rule.endpoint
+
+ return None
+
+ @property
+ def blueprint(self) -> str | None:
+ """The registered name of the current blueprint.
+
+ This will be ``None`` if the endpoint is not part of a
+ blueprint, or if URL matching failed or has not been performed
+ yet.
+
+ This does not necessarily match the name the blueprint was
+ created with. It may have been nested, or registered with a
+ different name.
+ """
+ endpoint = self.endpoint
+
+ if endpoint is not None and "." in endpoint:
+ return endpoint.rpartition(".")[0]
+
+ return None
+
+ @property
+ def blueprints(self) -> list[str]:
+ """The registered names of the current blueprint upwards through
+ parent blueprints.
+
+ This will be an empty list if there is no current blueprint, or
+ if URL matching failed.
+
+ .. versionadded:: 2.0.1
+ """
+ name = self.blueprint
+
+ if name is None:
+ return []
+
+ return _split_blueprint_path(name)
+
+ def _load_form_data(self) -> None:
+ super()._load_form_data()
+
+ # In debug mode we're replacing the files multidict with an ad-hoc
+ # subclass that raises a different error for key errors.
+ if (
+ current_app
+ and current_app.debug
+ and self.mimetype != "multipart/form-data"
+ and not self.files
+ ):
+ from .debughelpers import attach_enctype_error_multidict
+
+ attach_enctype_error_multidict(self)
+
+ def on_json_loading_failed(self, e: ValueError | None) -> t.Any:
+ try:
+ return super().on_json_loading_failed(e)
+ except BadRequest as e:
+ if current_app and current_app.debug:
+ raise
+
+ raise BadRequest() from e
+
+
+class Response(ResponseBase):
+ """The response object that is used by default in Flask. Works like the
+ response object from Werkzeug but is set to have an HTML mimetype by
+ default. Quite often you don't have to create this object yourself because
+ :meth:`~flask.Flask.make_response` will take care of that for you.
+
+ If you want to replace the response object used you can subclass this and
+ set :attr:`~flask.Flask.response_class` to your subclass.
+
+ .. versionchanged:: 1.0
+ JSON support is added to the response, like the request. This is useful
+ when testing to get the test client response data as JSON.
+
+ .. versionchanged:: 1.0
+
+ Added :attr:`max_cookie_size`.
+ """
+
+ default_mimetype: str | None = "text/html"
+
+ json_module = json
+
+ autocorrect_location_header = False
+
+ @property
+ def max_cookie_size(self) -> int: # type: ignore
+ """Read-only view of the :data:`MAX_COOKIE_SIZE` config key.
+
+ See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in
+ Werkzeug's docs.
+ """
+ if current_app:
+ return current_app.config["MAX_COOKIE_SIZE"] # type: ignore[no-any-return]
+
+ # return Werkzeug's default when not in an app context
+ return super().max_cookie_size
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/INSTALLER b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/LICENSE b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..562f7eb602f1966cfa4276aaf8d5956959091acc
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/LICENSE
@@ -0,0 +1,31 @@
+Copyright (c) 2010 by Armin Ronacher.
+
+Some rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+* The names of the contributors may not be used to endorse or
+ promote products derived from this software without specific
+ prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/METADATA b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..ae2e04f1a7636c8ce754b3ecc41fb8fa720d1385
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/METADATA
@@ -0,0 +1,49 @@
+Metadata-Version: 2.1
+Name: flask-babel
+Version: 4.0.0
+Summary: Adds i18n/l10n support for Flask applications.
+Home-page: https://github.com/python-babel/flask-babel
+License: BSD-3-Clause
+Author: Armin Ronacher
+Maintainer: Tyler Kennedy
+Maintainer-email: tk@tkte.ch
+Requires-Python: >=3.8,<4.0
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Dist: Babel (>=2.12)
+Requires-Dist: Flask (>=2.0)
+Requires-Dist: Jinja2 (>=3.1)
+Requires-Dist: pytz (>=2022.7)
+Project-URL: Documentation, https://python-babel.github.io/flask-babel/
+Project-URL: Repository, https://github.com/python-babel/flask-babel
+Description-Content-Type: text/markdown
+
+# Flask Babel
+
+
+[](https://pypi.python.org/pypi/Flask-Babel)
+
+Implements i18n and l10n support for Flask. This is based on the Python
+[babel][] and [pytz][] modules.
+
+## Documentation
+
+The latest documentation is available [here][docs].
+
+[babel]: https://github.com/python-babel/babel
+[pytz]: https://pypi.python.org/pypi/pytz/
+[docs]: https://python-babel.github.io/flask-babel/
+[semver]: https://semver.org/
+
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/RECORD b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..16f0aae66b51b633f777050406f3ad6ee05f75fc
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/RECORD
@@ -0,0 +1,10 @@
+flask_babel-4.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+flask_babel-4.0.0.dist-info/LICENSE,sha256=pSYQCnBHI3Ngo5S6T3CugBtQ_5uMm55z53lUgKWfa34,1457
+flask_babel-4.0.0.dist-info/METADATA,sha256=OPdrGKHwsbvTjCvlqZn8dqjydOI22y8eb5QTj5ouXqU,1935
+flask_babel-4.0.0.dist-info/RECORD,,
+flask_babel-4.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+flask_babel-4.0.0.dist-info/WHEEL,sha256=d2fvjOD7sXsVzChCqf0Ty0JbHKBaLYwDbGQDwQTnJ50,88
+flask_babel/__init__.py,sha256=8DtVq8EaWZ8zEKfsMFjOARtv8gKOaeXe397NyNxIubg,27138
+flask_babel/__pycache__/__init__.cpython-311.pyc,,
+flask_babel/__pycache__/speaklater.cpython-311.pyc,,
+flask_babel/speaklater.py,sha256=moGrHeg_M-c5sqUdmudwnKZ55-FH-Uh4iktpjiHGSpo,1669
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/REQUESTED b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/WHEEL b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..3695fd1473b2fb25c1cbe89250e443f498e8bc37
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel-4.0.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: poetry-core 1.7.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f94d22f0840a3d43bae99392dacf2fb0e2ab928
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel/__init__.py
@@ -0,0 +1,787 @@
+"""
+ flask_babel
+ ~~~~~~~~~~~
+
+ Implements i18n/l10n support for Flask applications based on Babel.
+
+ :copyright: (c) 2013 by Armin Ronacher, Daniel Neuhäuser.
+ :license: BSD, see LICENSE for more details.
+"""
+import os
+from dataclasses import dataclass
+from types import SimpleNamespace
+from datetime import datetime
+from contextlib import contextmanager
+from typing import List, Callable, Optional, Union
+
+from babel.support import Translations, NullTranslations
+from flask import current_app, g
+from babel import dates, numbers, support, Locale
+from pytz import timezone, UTC
+from werkzeug.datastructures import ImmutableDict
+from werkzeug.utils import cached_property
+
+from flask_babel.speaklater import LazyString
+
+
+@dataclass
+class BabelConfiguration:
+ """Application-specific configuration for Babel."""
+ default_locale: str
+ default_timezone: str
+ default_domain: str
+ default_directories: List[str]
+ translation_directories: List[str]
+
+ instance: 'Babel'
+
+ locale_selector: Optional[Callable] = None
+ timezone_selector: Optional[Callable] = None
+
+
+def get_babel(app=None) -> 'BabelConfiguration':
+ app = app or current_app
+ if not hasattr(app, 'extensions'):
+ app.extensions = {}
+ return app.extensions['babel']
+
+
+class Babel:
+ """Central controller class that can be used to configure how
+ Flask-Babel behaves. Each application that wants to use Flask-Babel
+ has to create, or run :meth:`init_app` on, an instance of this class
+ after the configuration was initialized.
+ """
+
+ default_date_formats = ImmutableDict({
+ 'time': 'medium',
+ 'date': 'medium',
+ 'datetime': 'medium',
+ 'time.short': None,
+ 'time.medium': None,
+ 'time.full': None,
+ 'time.long': None,
+ 'date.short': None,
+ 'date.medium': None,
+ 'date.full': None,
+ 'date.long': None,
+ 'datetime.short': None,
+ 'datetime.medium': None,
+ 'datetime.full': None,
+ 'datetime.long': None,
+ })
+
+ def __init__(self, app=None, date_formats=None, configure_jinja=True, *args,
+ **kwargs):
+ """Creates a new Babel instance.
+
+ If an application is passed, it will be configured with the provided
+ arguments. Otherwise, :meth:`init_app` can be used to configure the
+ application later.
+ """
+ self._configure_jinja = configure_jinja
+ self.date_formats = date_formats
+
+ if app is not None:
+ self.init_app(app, *args, **kwargs)
+
+ def init_app(self, app, default_locale='en', default_domain='messages',
+ default_translation_directories='translations',
+ default_timezone='UTC', locale_selector=None,
+ timezone_selector=None):
+ """
+ Initializes the Babel instance for use with this specific application.
+
+ :param app: The application to configure
+ :param default_locale: The default locale to use for this application
+ :param default_domain: The default domain to use for this application
+ :param default_translation_directories: The default translation
+ directories to use for this
+ application
+ :param default_timezone: The default timezone to use for this
+ application
+ :param locale_selector: The function to use to select the locale
+ for a request
+ :param timezone_selector: The function to use to select the
+ timezone for a request
+ """
+ if not hasattr(app, 'extensions'):
+ app.extensions = {}
+
+ directories = app.config.get(
+ 'BABEL_TRANSLATION_DIRECTORIES',
+ default_translation_directories
+ ).split(';')
+
+ app.extensions['babel'] = BabelConfiguration(
+ default_locale=app.config.get(
+ 'BABEL_DEFAULT_LOCALE',
+ default_locale
+ ),
+ default_timezone=app.config.get(
+ 'BABEL_DEFAULT_TIMEZONE',
+ default_timezone
+ ),
+ default_domain=app.config.get(
+ 'BABEL_DOMAIN',
+ default_domain
+ ),
+ default_directories=directories,
+ translation_directories=list(
+ self._resolve_directories(directories, app)
+ ),
+ instance=self,
+ locale_selector=locale_selector,
+ timezone_selector=timezone_selector
+ )
+
+ # a mapping of Babel datetime format strings that can be modified
+ # to change the defaults. If you invoke :func:`format_datetime`
+ # and do not provide any format string Flask-Babel will do the
+ # following things:
+ #
+ # 1. look up ``date_formats['datetime']``. By default, ``'medium'``
+ # is returned to enforce medium length datetime formats.
+ # 2. ``date_formats['datetime.medium'] (if ``'medium'`` was
+ # returned in step one) is looked up. If the return value
+ # is anything but `None` this is used as new format string.
+ # otherwise the default for that language is used.
+ if self.date_formats is None:
+ self.date_formats = self.default_date_formats.copy()
+
+ if self._configure_jinja:
+ app.jinja_env.filters.update(
+ datetimeformat=format_datetime,
+ dateformat=format_date,
+ timeformat=format_time,
+ timedeltaformat=format_timedelta,
+ numberformat=format_number,
+ decimalformat=format_decimal,
+ currencyformat=format_currency,
+ percentformat=format_percent,
+ scientificformat=format_scientific,
+ )
+ app.jinja_env.add_extension('jinja2.ext.i18n')
+ app.jinja_env.install_gettext_callables(
+ gettext=lambda s: get_translations().ugettext(s),
+ ngettext=lambda s, p, n: get_translations().ungettext(s, p, n),
+ newstyle=True,
+ pgettext=lambda c, s: get_translations().upgettext(c, s),
+ npgettext=lambda c, s, p, n: get_translations().unpgettext(
+ c, s, p, n
+ ),
+ )
+
+ def list_translations(self):
+ """Returns a list of all the locales translations exist for. The list
+ returned will be filled with actual locale objects and not just strings.
+
+ .. note::
+
+ The default locale will always be returned, even if no translation
+ files exist for it.
+
+ .. versionadded:: 0.6
+ """
+ result = []
+
+ for dirname in get_babel().translation_directories:
+ if not os.path.isdir(dirname):
+ continue
+
+ for folder in os.listdir(dirname):
+ locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES')
+ if not os.path.isdir(locale_dir):
+ continue
+
+ if any(x.endswith('.mo') for x in os.listdir(locale_dir)):
+ result.append(Locale.parse(folder))
+
+ if self.default_locale not in result:
+ result.append(self.default_locale)
+ return result
+
+ @property
+ def default_locale(self) -> Locale:
+ """The default locale from the configuration as an instance of a
+ `babel.Locale` object.
+ """
+ return Locale.parse(get_babel().default_locale)
+
+ @property
+ def default_timezone(self) -> timezone:
+ """The default timezone from the configuration as an instance of a
+ `pytz.timezone` object.
+ """
+ return timezone(get_babel().default_timezone)
+
+ @property
+ def domain(self) -> str:
+ """The message domain for the translations as a string.
+ """
+ return get_babel().default_domain
+
+ @cached_property
+ def domain_instance(self):
+ """The message domain for the translations.
+ """
+ return Domain(domain=self.domain)
+
+ @staticmethod
+ def _resolve_directories(directories: List[str], app=None):
+ for path in directories:
+ if os.path.isabs(path):
+ yield path
+ elif app is not None:
+ # We can only resolve relative paths if we have an application
+ # context.
+ yield os.path.join(app.root_path, path)
+
+
+def get_translations() -> Union[Translations, NullTranslations]:
+ """Returns the correct gettext translations that should be used for
+ this request. This will never fail and return a dummy translation
+ object if used outside the request or if a translation cannot be found.
+ """
+ return get_domain().get_translations()
+
+
+def get_locale() -> Optional[Locale]:
+ """Returns the locale that should be used for this request as
+ `babel.Locale` object. This returns `None` if used outside a request.
+ """
+ ctx = _get_current_context()
+ if ctx is None:
+ return None
+
+ locale = getattr(ctx, 'babel_locale', None)
+ if locale is None:
+ babel = get_babel()
+ if babel.locale_selector is None:
+ locale = babel.instance.default_locale
+ else:
+ rv = babel.locale_selector()
+ if rv is None:
+ locale = babel.instance.default_locale
+ else:
+ locale = Locale.parse(rv)
+ ctx.babel_locale = locale
+
+ return locale
+
+
+def get_timezone() -> Optional[timezone]:
+ """Returns the timezone that should be used for this request as
+ a `pytz.timezone` object. This returns `None` if used outside a request.
+ """
+ ctx = _get_current_context()
+ tzinfo = getattr(ctx, 'babel_tzinfo', None)
+ if tzinfo is None:
+ babel = get_babel()
+ if babel.timezone_selector is None:
+ tzinfo = babel.instance.default_timezone
+ else:
+ rv = babel.timezone_selector()
+ if rv is None:
+ tzinfo = babel.instance.default_timezone
+ else:
+ tzinfo = timezone(rv) if isinstance(rv, str) else rv
+ ctx.babel_tzinfo = tzinfo
+ return tzinfo
+
+
+def refresh():
+ """Refreshes the cached timezones and locale information. This can
+ be used to switch a translation between a request and if you want
+ the changes to take place immediately, not just with the next request::
+
+ user.timezone = request.form['timezone']
+ user.locale = request.form['locale']
+ refresh()
+ flash(gettext('Language was changed'))
+
+ Without that refresh, the :func:`~flask.flash` function would probably
+ return English text and a now German page.
+ """
+ ctx = _get_current_context()
+ for key in 'babel_locale', 'babel_tzinfo', 'babel_translations':
+ if hasattr(ctx, key):
+ delattr(ctx, key)
+
+ if hasattr(ctx, 'forced_babel_locale'):
+ ctx.babel_locale = ctx.forced_babel_locale
+
+
+@contextmanager
+def force_locale(locale):
+ """Temporarily overrides the currently selected locale.
+
+ Sometimes it is useful to switch the current locale to different one, do
+ some tasks and then revert back to the original one. For example, if the
+ user uses German on the website, but you want to email them in English,
+ you can use this function as a context manager::
+
+ with force_locale('en_US'):
+ send_email(gettext('Hello!'), ...)
+
+ :param locale: The locale to temporary switch to (ex: 'en_US').
+ """
+ ctx = _get_current_context()
+ if ctx is None:
+ yield
+ return
+
+ orig_attrs = {}
+ for key in ('babel_translations', 'babel_locale'):
+ orig_attrs[key] = getattr(ctx, key, None)
+
+ try:
+ ctx.babel_locale = Locale.parse(locale)
+ ctx.forced_babel_locale = ctx.babel_locale
+ ctx.babel_translations = None
+ yield
+ finally:
+ if hasattr(ctx, 'forced_babel_locale'):
+ del ctx.forced_babel_locale
+
+ for key, value in orig_attrs.items():
+ setattr(ctx, key, value)
+
+
+def _get_format(key, format) -> Optional[str]:
+ """A small helper for the datetime formatting functions. Looks up
+ format defaults for different kinds.
+ """
+ babel = get_babel()
+ if format is None:
+ format = babel.instance.date_formats[key]
+ if format in ('short', 'medium', 'full', 'long'):
+ rv = babel.instance.date_formats['%s.%s' % (key, format)]
+ if rv is not None:
+ format = rv
+ return format
+
+
+def to_user_timezone(datetime):
+ """Convert a datetime object to the user's timezone. This automatically
+ happens on all date formatting unless rebasing is disabled. If you need
+ to convert a :class:`datetime.datetime` object at any time to the user's
+ timezone (as returned by :func:`get_timezone`) this function can be used.
+ """
+ if datetime.tzinfo is None:
+ datetime = datetime.replace(tzinfo=UTC)
+ tzinfo = get_timezone()
+ return tzinfo.normalize(datetime.astimezone(tzinfo))
+
+
+def to_utc(datetime):
+ """Convert a datetime object to UTC and drop tzinfo. This is the
+ opposite operation to :func:`to_user_timezone`.
+ """
+ if datetime.tzinfo is None:
+ datetime = get_timezone().localize(datetime)
+ return datetime.astimezone(UTC).replace(tzinfo=None)
+
+
+def format_datetime(datetime=None, format=None, rebase=True):
+ """Return a date formatted according to the given pattern. If no
+ :class:`~datetime.datetime` object is passed, the current time is
+ assumed. By default, rebasing happens, which causes the object to
+ be converted to the user's timezone (as returned by
+ :func:`to_user_timezone`). This function formats both date and
+ time.
+
+ The format parameter can either be ``'short'``, ``'medium'``,
+ ``'long'`` or ``'full'`` (in which case the language's default for
+ that setting is used, or the default from the :attr:`Babel.date_formats`
+ mapping is used) or a format string as documented by Babel.
+
+ This function is also available in the template context as filter
+ named `datetimeformat`.
+ """
+ format = _get_format('datetime', format)
+ return _date_format(dates.format_datetime, datetime, format, rebase)
+
+
+def format_date(date=None, format=None, rebase=True):
+ """Return a date formatted according to the given pattern. If no
+ :class:`~datetime.datetime` or :class:`~datetime.date` object is passed,
+ the current time is assumed. By default, rebasing happens, which causes
+ the object to be converted to the users's timezone (as returned by
+ :func:`to_user_timezone`). This function only formats the date part
+ of a :class:`~datetime.datetime` object.
+
+ The format parameter can either be ``'short'``, ``'medium'``,
+ ``'long'`` or ``'full'`` (in which case the language's default for
+ that setting is used, or the default from the :attr:`Babel.date_formats`
+ mapping is used) or a format string as documented by Babel.
+
+ This function is also available in the template context as filter
+ named `dateformat`.
+ """
+ if rebase and isinstance(date, datetime):
+ date = to_user_timezone(date)
+ format = _get_format('date', format)
+ return _date_format(dates.format_date, date, format, rebase)
+
+
+def format_time(time=None, format=None, rebase=True):
+ """Return a time formatted according to the given pattern. If no
+ :class:`~datetime.datetime` object is passed, the current time is
+ assumed. By default, rebasing happens, which causes the object to
+ be converted to the user's timezone (as returned by
+ :func:`to_user_timezone`). This function formats both date and time.
+
+ The format parameter can either be ``'short'``, ``'medium'``,
+ ``'long'`` or ``'full'`` (in which case the language's default for
+ that setting is used, or the default from the :attr:`Babel.date_formats`
+ mapping is used) or a format string as documented by Babel.
+
+ This function is also available in the template context as filter
+ named `timeformat`.
+ """
+ format = _get_format('time', format)
+ return _date_format(dates.format_time, time, format, rebase)
+
+
+def format_timedelta(datetime_or_timedelta, granularity: str = 'second',
+ add_direction=False, threshold=0.85):
+ """Format the elapsed time from the given date to now or the given
+ timedelta.
+
+ This function is also available in the template context as filter
+ named `timedeltaformat`.
+ """
+ if isinstance(datetime_or_timedelta, datetime):
+ datetime_or_timedelta = datetime.utcnow() - datetime_or_timedelta
+ return dates.format_timedelta(
+ datetime_or_timedelta,
+ granularity,
+ threshold=threshold,
+ add_direction=add_direction,
+ locale=get_locale()
+ )
+
+
+def _date_format(formatter, obj, format, rebase, **extra):
+ """Internal helper that formats the date."""
+ locale = get_locale()
+ extra = {}
+ if formatter is not dates.format_date and rebase:
+ extra['tzinfo'] = get_timezone()
+ return formatter(obj, format, locale=locale, **extra)
+
+
+def format_number(number) -> str:
+ """Return the given number formatted for the locale in request
+
+ :param number: the number to format
+ :return: the formatted number
+ :rtype: unicode
+ """
+ locale = get_locale()
+ return numbers.format_decimal(number, locale=locale)
+
+
+def format_decimal(number, format=None) -> str:
+ """Return the given decimal number formatted for the locale in the request.
+
+ :param number: the number to format
+ :param format: the format to use
+ :return: the formatted number
+ :rtype: unicode
+ """
+ locale = get_locale()
+ return numbers.format_decimal(number, format=format, locale=locale)
+
+
+def format_currency(number, currency, format=None, currency_digits=True,
+ format_type='standard') -> str:
+ """Return the given number formatted for the locale in the request.
+
+ :param number: the number to format
+ :param currency: the currency code
+ :param format: the format to use
+ :param currency_digits: use the currency’s number of decimal digits
+ [default: True]
+ :param format_type: the currency format type to use
+ [default: standard]
+ :return: the formatted number
+ :rtype: unicode
+ """
+ locale = get_locale()
+ return numbers.format_currency(
+ number,
+ currency,
+ format=format,
+ locale=locale,
+ currency_digits=currency_digits,
+ format_type=format_type
+ )
+
+
+def format_percent(number, format=None) -> str:
+ """Return formatted percent value for the locale in the request.
+
+ :param number: the number to format
+ :param format: the format to use
+ :return: the formatted percent number
+ :rtype: unicode
+ """
+ locale = get_locale()
+ return numbers.format_percent(number, format=format, locale=locale)
+
+
+def format_scientific(number, format=None) -> str:
+ """Return value formatted in scientific notation for the locale in request
+
+ :param number: the number to format
+ :param format: the format to use
+ :return: the formatted percent number
+ :rtype: unicode
+ """
+ locale = get_locale()
+ return numbers.format_scientific(number, format=format, locale=locale)
+
+
+class Domain(object):
+ """Localization domain. By default, it will look for translations in the
+ Flask application directory and "messages" domain - all message catalogs
+ should be called ``messages.mo``.
+
+ Additional domains are supported passing a list of domain names to the
+ ``domain`` argument, but note that in this case they must match a list
+ passed to ``translation_directories``, eg::
+
+ Domain(
+ translation_directories=[
+ "/path/to/translations/with/messages/domain",
+ "/another/path/to/translations/with/another/domain",
+ ],
+ domains=[
+ "messages",
+ "myapp",
+ ]
+ )
+ """
+
+ def __init__(self, translation_directories=None, domain='messages'):
+ if isinstance(translation_directories, str):
+ translation_directories = [translation_directories]
+ self._translation_directories = translation_directories
+
+ self.domain = domain.split(';')
+
+ self.cache = {}
+
+ def __repr__(self):
+ return ''.format(
+ self._translation_directories,
+ self.domain
+ )
+
+ @property
+ def translation_directories(self):
+ if self._translation_directories is not None:
+ return self._translation_directories
+ return get_babel().translation_directories
+
+ def as_default(self):
+ """Set this domain as default for the current request"""
+ ctx = _get_current_context()
+
+ if ctx is None:
+ raise RuntimeError("No request context")
+
+ ctx.babel_domain = self
+
+ def get_translations_cache(self, ctx):
+ """Returns dictionary-like object for translation caching"""
+ return self.cache
+
+ def get_translations(self):
+ ctx = _get_current_context()
+
+ if ctx is None:
+ return support.NullTranslations()
+
+ cache = self.get_translations_cache(ctx)
+ locale = get_locale()
+ try:
+ return cache[str(locale), self.domain[0]]
+ except KeyError:
+ translations = support.Translations()
+
+ for index, dirname in enumerate(self.translation_directories):
+
+ domain = (
+ self.domain[0]
+ if len(self.domain) == 1
+ else self.domain[index]
+ )
+
+ catalog = support.Translations.load(
+ dirname,
+ [locale],
+ domain
+ )
+ translations.merge(catalog)
+ # FIXME: Workaround for merge() being really, really stupid. It
+ # does not copy _info, plural(), or any other instance variables
+ # populated by GNUTranslations. We probably want to stop using
+ # `support.Translations.merge` entirely.
+ if hasattr(catalog, 'plural'):
+ translations.plural = catalog.plural
+
+ cache[str(locale), self.domain[0]] = translations
+ return translations
+
+ def gettext(self, string, **variables):
+ """Translates a string with the current locale and passes in the
+ given keyword arguments as mapping to a string formatting string.
+
+ ::
+
+ gettext(u'Hello World!')
+ gettext(u'Hello %(name)s!', name='World')
+ """
+ t = self.get_translations()
+ s = t.ugettext(string)
+ return s if not variables else s % variables
+
+ def ngettext(self, singular, plural, num, **variables):
+ """Translates a string with the current locale and passes in the
+ given keyword arguments as mapping to a string formatting string.
+ The `num` parameter is used to dispatch between singular and various
+ plural forms of the message. It is available in the format string
+ as ``%(num)d`` or ``%(num)s``. The source language should be
+ English or a similar language which only has one plural form.
+
+ ::
+
+ ngettext(u'%(num)d Apple', u'%(num)d Apples', num=len(apples))
+ """
+ variables.setdefault('num', num)
+ t = self.get_translations()
+ s = t.ungettext(singular, plural, num)
+ return s if not variables else s % variables
+
+ def pgettext(self, context, string, **variables):
+ """Like :func:`gettext` but with a context.
+
+ .. versionadded:: 0.7
+ """
+ t = self.get_translations()
+ s = t.upgettext(context, string)
+ return s if not variables else s % variables
+
+ def npgettext(self, context, singular, plural, num, **variables):
+ """Like :func:`ngettext` but with a context.
+
+ .. versionadded:: 0.7
+ """
+ variables.setdefault('num', num)
+ t = self.get_translations()
+ s = t.unpgettext(context, singular, plural, num)
+ return s if not variables else s % variables
+
+ def lazy_gettext(self, string, **variables):
+ """Like :func:`gettext` but the string returned is lazy which means
+ it will be translated when it is used as an actual string.
+
+ Example::
+
+ hello = lazy_gettext(u'Hello World')
+
+ @app.route('/')
+ def index():
+ return unicode(hello)
+ """
+ return LazyString(self.gettext, string, **variables)
+
+ def lazy_ngettext(self, singular, plural, num, **variables):
+ """Like :func:`ngettext` but the string returned is lazy which means
+ it will be translated when it is used as an actual string.
+
+ Example::
+
+ apples = lazy_ngettext(
+ u'%(num)d Apple',
+ u'%(num)d Apples',
+ num=len(apples)
+ )
+
+ @app.route('/')
+ def index():
+ return unicode(apples)
+ """
+ return LazyString(self.ngettext, singular, plural, num, **variables)
+
+ def lazy_pgettext(self, context, string, **variables):
+ """Like :func:`pgettext` but the string returned is lazy which means
+ it will be translated when it is used as an actual string.
+
+ .. versionadded:: 0.7
+ """
+ return LazyString(self.pgettext, context, string, **variables)
+
+
+def _get_current_context() -> Optional[SimpleNamespace]:
+ if not g:
+ return None
+
+ if not hasattr(g, "_flask_babel"):
+ g._flask_babel = SimpleNamespace()
+
+ return g._flask_babel # noqa
+
+
+def get_domain() -> Domain:
+ ctx = _get_current_context()
+ if ctx is None:
+ # this will use NullTranslations
+ return Domain()
+
+ try:
+ return ctx.babel_domain
+ except AttributeError:
+ pass
+
+ ctx.babel_domain = get_babel().instance.domain_instance
+ return ctx.babel_domain
+
+
+# Create shortcuts for the default Flask domain
+def gettext(*args, **kwargs) -> str:
+ return get_domain().gettext(*args, **kwargs)
+
+
+_ = gettext
+
+
+def ngettext(*args, **kwargs) -> str:
+ return get_domain().ngettext(*args, **kwargs)
+
+
+def pgettext(*args, **kwargs) -> str:
+ return get_domain().pgettext(*args, **kwargs)
+
+
+def npgettext(*args, **kwargs) -> str:
+ return get_domain().npgettext(*args, **kwargs)
+
+
+def lazy_gettext(*args, **kwargs) -> LazyString:
+ return LazyString(gettext, *args, **kwargs)
+
+
+def lazy_pgettext(*args, **kwargs) -> LazyString:
+ return LazyString(pgettext, *args, **kwargs)
+
+
+def lazy_ngettext(*args, **kwargs) -> LazyString:
+ return LazyString(ngettext, *args, **kwargs)
+
+
+def lazy_npgettext(*args, **kwargs) -> LazyString:
+ return LazyString(npgettext, *args, **kwargs)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel/speaklater.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel/speaklater.py
new file mode 100644
index 0000000000000000000000000000000000000000..46bd272501276b4a8a8f0148e2e9399e81dc4263
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_babel/speaklater.py
@@ -0,0 +1,75 @@
+class LazyString(object):
+ def __init__(self, func, *args, **kwargs):
+ self._func = func
+ self._args = args
+ self._kwargs = kwargs
+
+ def __getattr__(self, attr):
+ if attr == "__setstate__":
+ raise AttributeError(attr)
+
+ string = str(self)
+ if hasattr(string, attr):
+ return getattr(string, attr)
+
+ raise AttributeError(attr)
+
+ def __repr__(self):
+ return "l'{0}'".format(str(self))
+
+ def __str__(self):
+ return str(self._func(*self._args, **self._kwargs))
+
+ def __len__(self):
+ return len(str(self))
+
+ def __getitem__(self, key):
+ return str(self)[key]
+
+ def __iter__(self):
+ return iter(str(self))
+
+ def __contains__(self, item):
+ return item in str(self)
+
+ def __add__(self, other):
+ return str(self) + other
+
+ def __radd__(self, other):
+ return other + str(self)
+
+ def __mul__(self, other):
+ return str(self) * other
+
+ def __rmul__(self, other):
+ return other * str(self)
+
+ def __lt__(self, other):
+ return str(self) < other
+
+ def __le__(self, other):
+ return str(self) <= other
+
+ def __eq__(self, other):
+ return str(self) == other
+
+ def __ne__(self, other):
+ return str(self) != other
+
+ def __gt__(self, other):
+ return str(self) > other
+
+ def __ge__(self, other):
+ return str(self) >= other
+
+ def __html__(self):
+ return str(self)
+
+ def __hash__(self):
+ return hash(str(self))
+
+ def __mod__(self, other):
+ return str(self) % other
+
+ def __rmod__(self, other):
+ return other + str(self)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a643ec4ed23b2853f17f08eb857306f7260ddf5
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/__init__.py
@@ -0,0 +1,9 @@
+from .flask_compress import Compress
+
+# _version.py is generated by setuptools_scm when building the package, it is not versioned.
+# If missing, this means that the imported code was most likely the git repository, that was
+# installed without the "editable" mode.
+try:
+ from ._version import __version__
+except ImportError:
+ __version__ = "0"
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/_version.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..c97e2bf441058f0d924cb17d410e64eb2d4b1f35
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/_version.py
@@ -0,0 +1 @@
+__version__ = "1.15"
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/flask_compress.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/flask_compress.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cfb59d6a2768ec991322f351421f94b88515ef5
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_compress/flask_compress.py
@@ -0,0 +1,253 @@
+
+# Authors: William Fagan
+# Copyright (c) 2013-2017 William Fagan
+# License: The MIT License (MIT)
+
+import sys
+import functools
+from gzip import GzipFile
+import zlib
+from io import BytesIO
+
+from collections import defaultdict
+
+try:
+ import brotlicffi as brotli
+except ImportError:
+ import brotli
+
+import zstandard
+
+from flask import request, after_this_request, current_app
+
+
+if sys.version_info[:2] == (2, 6):
+ class GzipFile(GzipFile):
+ """ Backport of context manager support for python 2.6"""
+ def __enter__(self):
+ if self.fileobj is None:
+ raise ValueError("I/O operation on closed GzipFile object")
+ return self
+
+ def __exit__(self, *args):
+ self.close()
+
+
+class DictCache(object):
+
+ def __init__(self):
+ self.data = {}
+
+ def get(self, key):
+ return self.data.get(key)
+
+ def set(self, key, value):
+ self.data[key] = value
+
+
+class Compress(object):
+ """
+ The Compress object allows your application to use Flask-Compress.
+
+ When initialising a Compress object you may optionally provide your
+ :class:`flask.Flask` application object if it is ready. Otherwise,
+ you may provide it later by using the :meth:`init_app` method.
+
+ :param app: optional :class:`flask.Flask` application object
+ :type app: :class:`flask.Flask` or None
+ """
+ def __init__(self, app=None):
+ """
+ An alternative way to pass your :class:`flask.Flask` application
+ object to Flask-Compress. :meth:`init_app` also takes care of some
+ default `settings`_.
+
+ :param app: the :class:`flask.Flask` application object.
+ """
+ self.app = app
+ if app is not None:
+ self.init_app(app)
+
+ def init_app(self, app):
+ defaults = [
+ ('COMPRESS_MIMETYPES', [
+ 'application/javascript', # Obsolete (RFC 9239)
+ 'application/json',
+ 'text/css',
+ 'text/html',
+ 'text/javascript',
+ 'text/xml',
+ ]),
+ ('COMPRESS_LEVEL', 6),
+ ('COMPRESS_BR_LEVEL', 4),
+ ('COMPRESS_BR_MODE', 0),
+ ('COMPRESS_BR_WINDOW', 22),
+ ('COMPRESS_BR_BLOCK', 0),
+ ('COMPRESS_ZSTD_LEVEL', 3),
+ ('COMPRESS_DEFLATE_LEVEL', -1),
+ ('COMPRESS_MIN_SIZE', 500),
+ ('COMPRESS_CACHE_KEY', None),
+ ('COMPRESS_CACHE_BACKEND', None),
+ ('COMPRESS_REGISTER', True),
+ ('COMPRESS_STREAMS', True),
+ ('COMPRESS_ALGORITHM', ['zstd', 'br', 'gzip', 'deflate']),
+ ]
+
+ for k, v in defaults:
+ app.config.setdefault(k, v)
+
+ backend = app.config['COMPRESS_CACHE_BACKEND']
+ self.cache = backend() if backend else None
+ self.cache_key = app.config['COMPRESS_CACHE_KEY']
+
+ algo = app.config['COMPRESS_ALGORITHM']
+ if isinstance(algo, str):
+ self.enabled_algorithms = [i.strip() for i in algo.split(',')]
+ else:
+ self.enabled_algorithms = list(algo)
+
+ if (app.config['COMPRESS_REGISTER'] and
+ app.config['COMPRESS_MIMETYPES']):
+ app.after_request(self.after_request)
+
+ def _choose_compress_algorithm(self, accept_encoding_header):
+ """
+ Determine which compression algorithm we're going to use based on the
+ client request. The `Accept-Encoding` header may list one or more desired
+ algorithms, together with a "quality factor" for each one (higher quality
+ means the client prefers that algorithm more).
+
+ :param accept_encoding_header: Content of the `Accept-Encoding` header
+ :return: name of a compression algorithm (`gzip`, `deflate`, `br`, 'zstd') or `None` if
+ the client and server don't agree on any.
+ """
+ # A flag denoting that client requested using any (`*`) algorithm,
+ # in case a specific one is not supported by the server
+ fallback_to_any = False
+
+ # Map quality factors to requested algorithm names.
+ algos_by_quality = defaultdict(set)
+
+ # Set of supported algorithms
+ server_algos_set = set(self.enabled_algorithms)
+
+ for part in accept_encoding_header.lower().split(','):
+ part = part.strip()
+ if ';q=' in part:
+ # If the client associated a quality factor with an algorithm,
+ # try to parse it. We could do the matching using a regex, but
+ # the format is so simple that it would be overkill.
+ algo = part.split(';')[0].strip()
+ try:
+ quality = float(part.split('=')[1].strip())
+ except ValueError:
+ quality = 1.0
+ else:
+ # Otherwise, use the default quality
+ algo = part
+ quality = 1.0
+
+ if algo == '*':
+ if quality > 0:
+ fallback_to_any = True
+ elif algo == 'identity': # identity means 'no compression asked'
+ algos_by_quality[quality].add(None)
+ elif algo in server_algos_set:
+ algos_by_quality[quality].add(algo)
+
+ # Choose the algorithm with the highest quality factor that the server supports.
+ #
+ # If there are multiple equally good options, choose the first supported algorithm
+ # from server configuration.
+ #
+ # If the server doesn't support any algorithm that the client requested but
+ # there's a special wildcard algorithm request (`*`), choose the first supported
+ # algorithm.
+ for _, viable_algos in sorted(algos_by_quality.items(), reverse=True):
+ if len(viable_algos) == 1:
+ return viable_algos.pop()
+ elif len(viable_algos) > 1:
+ for server_algo in self.enabled_algorithms:
+ if server_algo in viable_algos:
+ return server_algo
+
+ if fallback_to_any:
+ return self.enabled_algorithms[0]
+ return None
+
+ def after_request(self, response):
+ app = self.app or current_app
+
+ vary = response.headers.get('Vary')
+ if not vary:
+ response.headers['Vary'] = 'Accept-Encoding'
+ elif 'accept-encoding' not in vary.lower():
+ response.headers['Vary'] = '{}, Accept-Encoding'.format(vary)
+
+ accept_encoding = request.headers.get('Accept-Encoding', '')
+ chosen_algorithm = self._choose_compress_algorithm(accept_encoding)
+
+ if (chosen_algorithm is None or
+ response.mimetype not in app.config["COMPRESS_MIMETYPES"] or
+ response.status_code < 200 or
+ response.status_code >= 300 or
+ (response.is_streamed and app.config["COMPRESS_STREAMS"] is False) or
+ "Content-Encoding" in response.headers or
+ (response.content_length is not None and
+ response.content_length < app.config["COMPRESS_MIN_SIZE"])):
+ return response
+
+ response.direct_passthrough = False
+
+ if self.cache is not None:
+ key = self.cache_key(request)
+ compressed_content = self.cache.get(key)
+ if compressed_content is None:
+ compressed_content = self.compress(app, response, chosen_algorithm)
+ self.cache.set(key, compressed_content)
+ else:
+ compressed_content = self.compress(app, response, chosen_algorithm)
+
+ response.set_data(compressed_content)
+
+ response.headers['Content-Encoding'] = chosen_algorithm
+ response.headers['Content-Length'] = response.content_length
+
+ # "123456789" => "123456789:gzip" - A strong ETag validator
+ # W/"123456789" => W/"123456789:gzip" - A weak ETag validator
+ etag = response.headers.get('ETag')
+ if etag:
+ response.headers['ETag'] = '{0}:{1}"'.format(etag[:-1], chosen_algorithm)
+
+ return response
+
+ def compressed(self):
+ def decorator(f):
+ @functools.wraps(f)
+ def decorated_function(*args, **kwargs):
+ @after_this_request
+ def compressor(response):
+ return self.after_request(response)
+ return f(*args, **kwargs)
+ return decorated_function
+ return decorator
+
+ def compress(self, app, response, algorithm):
+ if algorithm == 'gzip':
+ gzip_buffer = BytesIO()
+ with GzipFile(mode='wb',
+ compresslevel=app.config['COMPRESS_LEVEL'],
+ fileobj=gzip_buffer) as gzip_file:
+ gzip_file.write(response.get_data())
+ return gzip_buffer.getvalue()
+ elif algorithm == 'deflate':
+ return zlib.compress(response.get_data(),
+ app.config['COMPRESS_DEFLATE_LEVEL'])
+ elif algorithm == 'br':
+ return brotli.compress(response.get_data(),
+ mode=app.config['COMPRESS_BR_MODE'],
+ quality=app.config['COMPRESS_BR_LEVEL'],
+ lgwin=app.config['COMPRESS_BR_WINDOW'],
+ lgblock=app.config['COMPRESS_BR_BLOCK'])
+ elif algorithm == 'zstd':
+ return zstandard.ZstdCompressor(app.config['COMPRESS_ZSTD_LEVEL']).compress(response.get_data())
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/__about__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/__about__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1918d54f750466ebdbb723b6b03edaee46a36af7
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/__about__.py
@@ -0,0 +1,10 @@
+__title__ = "Flask-Login"
+__description__ = "User session management for Flask"
+__url__ = "https://github.com/maxcountryman/flask-login"
+__version_info__ = ("0", "6", "3")
+__version__ = ".".join(__version_info__)
+__author__ = "Matthew Frazier"
+__author_email__ = "leafstormrush@gmail.com"
+__maintainer__ = "Max Countryman"
+__license__ = "MIT"
+__copyright__ = "(c) 2011 by Matthew Frazier"
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbe9c3e774e2bfae66550522b405612a585a9a2a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/__init__.py
@@ -0,0 +1,94 @@
+from .__about__ import __version__
+from .config import AUTH_HEADER_NAME
+from .config import COOKIE_DURATION
+from .config import COOKIE_HTTPONLY
+from .config import COOKIE_NAME
+from .config import COOKIE_SECURE
+from .config import ID_ATTRIBUTE
+from .config import LOGIN_MESSAGE
+from .config import LOGIN_MESSAGE_CATEGORY
+from .config import REFRESH_MESSAGE
+from .config import REFRESH_MESSAGE_CATEGORY
+from .login_manager import LoginManager
+from .mixins import AnonymousUserMixin
+from .mixins import UserMixin
+from .signals import session_protected
+from .signals import user_accessed
+from .signals import user_loaded_from_cookie
+from .signals import user_loaded_from_request
+from .signals import user_logged_in
+from .signals import user_logged_out
+from .signals import user_login_confirmed
+from .signals import user_needs_refresh
+from .signals import user_unauthorized
+from .test_client import FlaskLoginClient
+from .utils import confirm_login
+from .utils import current_user
+from .utils import decode_cookie
+from .utils import encode_cookie
+from .utils import fresh_login_required
+from .utils import login_fresh
+from .utils import login_remembered
+from .utils import login_required
+from .utils import login_url
+from .utils import login_user
+from .utils import logout_user
+from .utils import make_next_param
+from .utils import set_login_view
+
+__all__ = [
+ "__version__",
+ "AUTH_HEADER_NAME",
+ "COOKIE_DURATION",
+ "COOKIE_HTTPONLY",
+ "COOKIE_NAME",
+ "COOKIE_SECURE",
+ "ID_ATTRIBUTE",
+ "LOGIN_MESSAGE",
+ "LOGIN_MESSAGE_CATEGORY",
+ "REFRESH_MESSAGE",
+ "REFRESH_MESSAGE_CATEGORY",
+ "LoginManager",
+ "AnonymousUserMixin",
+ "UserMixin",
+ "session_protected",
+ "user_accessed",
+ "user_loaded_from_cookie",
+ "user_loaded_from_request",
+ "user_logged_in",
+ "user_logged_out",
+ "user_login_confirmed",
+ "user_needs_refresh",
+ "user_unauthorized",
+ "FlaskLoginClient",
+ "confirm_login",
+ "current_user",
+ "decode_cookie",
+ "encode_cookie",
+ "fresh_login_required",
+ "login_fresh",
+ "login_remembered",
+ "login_required",
+ "login_url",
+ "login_user",
+ "logout_user",
+ "make_next_param",
+ "set_login_view",
+]
+
+
+def __getattr__(name):
+ if name == "user_loaded_from_header":
+ import warnings
+ from .signals import _user_loaded_from_header
+
+ warnings.warn(
+ "'user_loaded_from_header' is deprecated and will be"
+ " removed in Flask-Login 0.7. Use"
+ " 'user_loaded_from_request' instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _user_loaded_from_header
+
+ raise AttributeError(name)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/config.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe2db2c5c8b3a6577fde3c4983a2ed3a8c515a1e
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/config.py
@@ -0,0 +1,55 @@
+from datetime import timedelta
+
+#: The default name of the "remember me" cookie (``remember_token``)
+COOKIE_NAME = "remember_token"
+
+#: The default time before the "remember me" cookie expires (365 days).
+COOKIE_DURATION = timedelta(days=365)
+
+#: Whether the "remember me" cookie requires Secure; defaults to ``False``
+COOKIE_SECURE = False
+
+#: Whether the "remember me" cookie uses HttpOnly or not; defaults to ``True``
+COOKIE_HTTPONLY = True
+
+#: Whether the "remember me" cookie requires same origin; defaults to ``None``
+COOKIE_SAMESITE = None
+
+#: The default flash message to display when users need to log in.
+LOGIN_MESSAGE = "Please log in to access this page."
+
+#: The default flash message category to display when users need to log in.
+LOGIN_MESSAGE_CATEGORY = "message"
+
+#: The default flash message to display when users need to reauthenticate.
+REFRESH_MESSAGE = "Please reauthenticate to access this page."
+
+#: The default flash message category to display when users need to
+#: reauthenticate.
+REFRESH_MESSAGE_CATEGORY = "message"
+
+#: The default attribute to retreive the str id of the user
+ID_ATTRIBUTE = "get_id"
+
+#: Default name of the auth header (``Authorization``)
+AUTH_HEADER_NAME = "Authorization"
+
+#: A set of session keys that are populated by Flask-Login. Use this set to
+#: purge keys safely and accurately.
+SESSION_KEYS = {
+ "_user_id",
+ "_remember",
+ "_remember_seconds",
+ "_id",
+ "_fresh",
+ "next",
+}
+
+#: A set of HTTP methods which are exempt from `login_required` and
+#: `fresh_login_required`. By default, this is just ``OPTIONS``.
+EXEMPT_METHODS = {"OPTIONS"}
+
+#: If true, the page the user is attempting to access is stored in the session
+#: rather than a url parameter when redirecting to the login view; defaults to
+#: ``False``.
+USE_SESSION_FOR_NEXT = False
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/login_manager.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/login_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..49d0844fa50bbb060f1f5d2d16ee89aeaa213b69
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/login_manager.py
@@ -0,0 +1,543 @@
+from datetime import datetime
+from datetime import timedelta
+
+from flask import abort
+from flask import current_app
+from flask import flash
+from flask import g
+from flask import has_app_context
+from flask import redirect
+from flask import request
+from flask import session
+
+from .config import AUTH_HEADER_NAME
+from .config import COOKIE_DURATION
+from .config import COOKIE_HTTPONLY
+from .config import COOKIE_NAME
+from .config import COOKIE_SAMESITE
+from .config import COOKIE_SECURE
+from .config import ID_ATTRIBUTE
+from .config import LOGIN_MESSAGE
+from .config import LOGIN_MESSAGE_CATEGORY
+from .config import REFRESH_MESSAGE
+from .config import REFRESH_MESSAGE_CATEGORY
+from .config import SESSION_KEYS
+from .config import USE_SESSION_FOR_NEXT
+from .mixins import AnonymousUserMixin
+from .signals import session_protected
+from .signals import user_accessed
+from .signals import user_loaded_from_cookie
+from .signals import user_loaded_from_request
+from .signals import user_needs_refresh
+from .signals import user_unauthorized
+from .utils import _create_identifier
+from .utils import _user_context_processor
+from .utils import decode_cookie
+from .utils import encode_cookie
+from .utils import expand_login_view
+from .utils import login_url as make_login_url
+from .utils import make_next_param
+
+
+class LoginManager:
+ """This object is used to hold the settings used for logging in. Instances
+ of :class:`LoginManager` are *not* bound to specific apps, so you can
+ create one in the main body of your code and then bind it to your
+ app in a factory function.
+ """
+
+ def __init__(self, app=None, add_context_processor=True):
+ #: A class or factory function that produces an anonymous user, which
+ #: is used when no one is logged in.
+ self.anonymous_user = AnonymousUserMixin
+
+ #: The name of the view to redirect to when the user needs to log in.
+ #: (This can be an absolute URL as well, if your authentication
+ #: machinery is external to your application.)
+ self.login_view = None
+
+ #: Names of views to redirect to when the user needs to log in,
+ #: per blueprint. If the key value is set to None the value of
+ #: :attr:`login_view` will be used instead.
+ self.blueprint_login_views = {}
+
+ #: The message to flash when a user is redirected to the login page.
+ self.login_message = LOGIN_MESSAGE
+
+ #: The message category to flash when a user is redirected to the login
+ #: page.
+ self.login_message_category = LOGIN_MESSAGE_CATEGORY
+
+ #: The name of the view to redirect to when the user needs to
+ #: reauthenticate.
+ self.refresh_view = None
+
+ #: The message to flash when a user is redirected to the 'needs
+ #: refresh' page.
+ self.needs_refresh_message = REFRESH_MESSAGE
+
+ #: The message category to flash when a user is redirected to the
+ #: 'needs refresh' page.
+ self.needs_refresh_message_category = REFRESH_MESSAGE_CATEGORY
+
+ #: The mode to use session protection in. This can be either
+ #: ``'basic'`` (the default) or ``'strong'``, or ``None`` to disable
+ #: it.
+ self.session_protection = "basic"
+
+ #: If present, used to translate flash messages ``self.login_message``
+ #: and ``self.needs_refresh_message``
+ self.localize_callback = None
+
+ self.unauthorized_callback = None
+
+ self.needs_refresh_callback = None
+
+ self.id_attribute = ID_ATTRIBUTE
+
+ self._user_callback = None
+
+ self._header_callback = None
+
+ self._request_callback = None
+
+ self._session_identifier_generator = _create_identifier
+
+ if app is not None:
+ self.init_app(app, add_context_processor)
+
+ def setup_app(self, app, add_context_processor=True): # pragma: no cover
+ """
+ This method has been deprecated. Please use
+ :meth:`LoginManager.init_app` instead.
+ """
+ import warnings
+
+ warnings.warn(
+ "'setup_app' is deprecated and will be removed in"
+ " Flask-Login 0.7. Use 'init_app' instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self.init_app(app, add_context_processor)
+
+ def init_app(self, app, add_context_processor=True):
+ """
+ Configures an application. This registers an `after_request` call, and
+ attaches this `LoginManager` to it as `app.login_manager`.
+
+ :param app: The :class:`flask.Flask` object to configure.
+ :type app: :class:`flask.Flask`
+ :param add_context_processor: Whether to add a context processor to
+ the app that adds a `current_user` variable to the template.
+ Defaults to ``True``.
+ :type add_context_processor: bool
+ """
+ app.login_manager = self
+ app.after_request(self._update_remember_cookie)
+
+ if add_context_processor:
+ app.context_processor(_user_context_processor)
+
+ def unauthorized(self):
+ """
+ This is called when the user is required to log in. If you register a
+ callback with :meth:`LoginManager.unauthorized_handler`, then it will
+ be called. Otherwise, it will take the following actions:
+
+ - Flash :attr:`LoginManager.login_message` to the user.
+
+ - If the app is using blueprints find the login view for
+ the current blueprint using `blueprint_login_views`. If the app
+ is not using blueprints or the login view for the current
+ blueprint is not specified use the value of `login_view`.
+
+ - Redirect the user to the login view. (The page they were
+ attempting to access will be passed in the ``next`` query
+ string variable, so you can redirect there if present instead
+ of the homepage. Alternatively, it will be added to the session
+ as ``next`` if USE_SESSION_FOR_NEXT is set.)
+
+ If :attr:`LoginManager.login_view` is not defined, then it will simply
+ raise a HTTP 401 (Unauthorized) error instead.
+
+ This should be returned from a view or before/after_request function,
+ otherwise the redirect will have no effect.
+ """
+ user_unauthorized.send(current_app._get_current_object())
+
+ if self.unauthorized_callback:
+ return self.unauthorized_callback()
+
+ if request.blueprint in self.blueprint_login_views:
+ login_view = self.blueprint_login_views[request.blueprint]
+ else:
+ login_view = self.login_view
+
+ if not login_view:
+ abort(401)
+
+ if self.login_message:
+ if self.localize_callback is not None:
+ flash(
+ self.localize_callback(self.login_message),
+ category=self.login_message_category,
+ )
+ else:
+ flash(self.login_message, category=self.login_message_category)
+
+ config = current_app.config
+ if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
+ login_url = expand_login_view(login_view)
+ session["_id"] = self._session_identifier_generator()
+ session["next"] = make_next_param(login_url, request.url)
+ redirect_url = make_login_url(login_view)
+ else:
+ redirect_url = make_login_url(login_view, next_url=request.url)
+
+ return redirect(redirect_url)
+
+ def user_loader(self, callback):
+ """
+ This sets the callback for reloading a user from the session. The
+ function you set should take a user ID (a ``str``) and return a
+ user object, or ``None`` if the user does not exist.
+
+ :param callback: The callback for retrieving a user object.
+ :type callback: callable
+ """
+ self._user_callback = callback
+ return self.user_callback
+
+ @property
+ def user_callback(self):
+ """Gets the user_loader callback set by user_loader decorator."""
+ return self._user_callback
+
+ def request_loader(self, callback):
+ """
+ This sets the callback for loading a user from a Flask request.
+ The function you set should take Flask request object and
+ return a user object, or `None` if the user does not exist.
+
+ :param callback: The callback for retrieving a user object.
+ :type callback: callable
+ """
+ self._request_callback = callback
+ return self.request_callback
+
+ @property
+ def request_callback(self):
+ """Gets the request_loader callback set by request_loader decorator."""
+ return self._request_callback
+
+ def unauthorized_handler(self, callback):
+ """
+ This will set the callback for the `unauthorized` method, which among
+ other things is used by `login_required`. It takes no arguments, and
+ should return a response to be sent to the user instead of their
+ normal view.
+
+ :param callback: The callback for unauthorized users.
+ :type callback: callable
+ """
+ self.unauthorized_callback = callback
+ return callback
+
+ def needs_refresh_handler(self, callback):
+ """
+ This will set the callback for the `needs_refresh` method, which among
+ other things is used by `fresh_login_required`. It takes no arguments,
+ and should return a response to be sent to the user instead of their
+ normal view.
+
+ :param callback: The callback for unauthorized users.
+ :type callback: callable
+ """
+ self.needs_refresh_callback = callback
+ return callback
+
+ def needs_refresh(self):
+ """
+ This is called when the user is logged in, but they need to be
+ reauthenticated because their session is stale. If you register a
+ callback with `needs_refresh_handler`, then it will be called.
+ Otherwise, it will take the following actions:
+
+ - Flash :attr:`LoginManager.needs_refresh_message` to the user.
+
+ - Redirect the user to :attr:`LoginManager.refresh_view`. (The page
+ they were attempting to access will be passed in the ``next``
+ query string variable, so you can redirect there if present
+ instead of the homepage.)
+
+ If :attr:`LoginManager.refresh_view` is not defined, then it will
+ simply raise a HTTP 401 (Unauthorized) error instead.
+
+ This should be returned from a view or before/after_request function,
+ otherwise the redirect will have no effect.
+ """
+ user_needs_refresh.send(current_app._get_current_object())
+
+ if self.needs_refresh_callback:
+ return self.needs_refresh_callback()
+
+ if not self.refresh_view:
+ abort(401)
+
+ if self.needs_refresh_message:
+ if self.localize_callback is not None:
+ flash(
+ self.localize_callback(self.needs_refresh_message),
+ category=self.needs_refresh_message_category,
+ )
+ else:
+ flash(
+ self.needs_refresh_message,
+ category=self.needs_refresh_message_category,
+ )
+
+ config = current_app.config
+ if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
+ login_url = expand_login_view(self.refresh_view)
+ session["_id"] = self._session_identifier_generator()
+ session["next"] = make_next_param(login_url, request.url)
+ redirect_url = make_login_url(self.refresh_view)
+ else:
+ login_url = self.refresh_view
+ redirect_url = make_login_url(login_url, next_url=request.url)
+
+ return redirect(redirect_url)
+
+ def header_loader(self, callback):
+ """
+ This function has been deprecated. Please use
+ :meth:`LoginManager.request_loader` instead.
+
+ This sets the callback for loading a user from a header value.
+ The function you set should take an authentication token and
+ return a user object, or `None` if the user does not exist.
+
+ :param callback: The callback for retrieving a user object.
+ :type callback: callable
+ """
+ import warnings
+
+ warnings.warn(
+ "'header_loader' is deprecated and will be removed in"
+ " Flask-Login 0.7. Use 'request_loader' instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self._header_callback = callback
+ return callback
+
+ def _update_request_context_with_user(self, user=None):
+ """Store the given user as ctx.user."""
+
+ if user is None:
+ user = self.anonymous_user()
+
+ g._login_user = user
+
+ def _load_user(self):
+ """Loads user from session or remember_me cookie as applicable"""
+
+ if self._user_callback is None and self._request_callback is None:
+ raise Exception(
+ "Missing user_loader or request_loader. Refer to "
+ "http://flask-login.readthedocs.io/#how-it-works "
+ "for more info."
+ )
+
+ user_accessed.send(current_app._get_current_object())
+
+ # Check SESSION_PROTECTION
+ if self._session_protection_failed():
+ return self._update_request_context_with_user()
+
+ user = None
+
+ # Load user from Flask Session
+ user_id = session.get("_user_id")
+ if user_id is not None and self._user_callback is not None:
+ user = self._user_callback(user_id)
+
+ # Load user from Remember Me Cookie or Request Loader
+ if user is None:
+ config = current_app.config
+ cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
+ header_name = config.get("AUTH_HEADER_NAME", AUTH_HEADER_NAME)
+ has_cookie = (
+ cookie_name in request.cookies and session.get("_remember") != "clear"
+ )
+ if has_cookie:
+ cookie = request.cookies[cookie_name]
+ user = self._load_user_from_remember_cookie(cookie)
+ elif self._request_callback:
+ user = self._load_user_from_request(request)
+ elif header_name in request.headers:
+ header = request.headers[header_name]
+ user = self._load_user_from_header(header)
+
+ return self._update_request_context_with_user(user)
+
+ def _session_protection_failed(self):
+ sess = session._get_current_object()
+ ident = self._session_identifier_generator()
+
+ app = current_app._get_current_object()
+ mode = app.config.get("SESSION_PROTECTION", self.session_protection)
+
+ if not mode or mode not in ["basic", "strong"]:
+ return False
+
+ # if the sess is empty, it's an anonymous user or just logged out
+ # so we can skip this
+ if sess and ident != sess.get("_id", None):
+ if mode == "basic" or sess.permanent:
+ if sess.get("_fresh") is not False:
+ sess["_fresh"] = False
+ session_protected.send(app)
+ return False
+ elif mode == "strong":
+ for k in SESSION_KEYS:
+ sess.pop(k, None)
+
+ sess["_remember"] = "clear"
+ session_protected.send(app)
+ return True
+
+ return False
+
+ def _load_user_from_remember_cookie(self, cookie):
+ user_id = decode_cookie(cookie)
+ if user_id is not None:
+ session["_user_id"] = user_id
+ session["_fresh"] = False
+ user = None
+ if self._user_callback:
+ user = self._user_callback(user_id)
+ if user is not None:
+ app = current_app._get_current_object()
+ user_loaded_from_cookie.send(app, user=user)
+ return user
+ return None
+
+ def _load_user_from_header(self, header):
+ if self._header_callback:
+ user = self._header_callback(header)
+ if user is not None:
+ app = current_app._get_current_object()
+
+ from .signals import _user_loaded_from_header
+
+ _user_loaded_from_header.send(app, user=user)
+ return user
+ return None
+
+ def _load_user_from_request(self, request):
+ if self._request_callback:
+ user = self._request_callback(request)
+ if user is not None:
+ app = current_app._get_current_object()
+ user_loaded_from_request.send(app, user=user)
+ return user
+ return None
+
+ def _update_remember_cookie(self, response):
+ # Don't modify the session unless there's something to do.
+ if "_remember" not in session and current_app.config.get(
+ "REMEMBER_COOKIE_REFRESH_EACH_REQUEST"
+ ):
+ session["_remember"] = "set"
+
+ if "_remember" in session:
+ operation = session.pop("_remember", None)
+
+ if operation == "set" and "_user_id" in session:
+ self._set_cookie(response)
+ elif operation == "clear":
+ self._clear_cookie(response)
+
+ return response
+
+ def _set_cookie(self, response):
+ # cookie settings
+ config = current_app.config
+ cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
+ domain = config.get("REMEMBER_COOKIE_DOMAIN")
+ path = config.get("REMEMBER_COOKIE_PATH", "/")
+
+ secure = config.get("REMEMBER_COOKIE_SECURE", COOKIE_SECURE)
+ httponly = config.get("REMEMBER_COOKIE_HTTPONLY", COOKIE_HTTPONLY)
+ samesite = config.get("REMEMBER_COOKIE_SAMESITE", COOKIE_SAMESITE)
+
+ if "_remember_seconds" in session:
+ duration = timedelta(seconds=session["_remember_seconds"])
+ else:
+ duration = config.get("REMEMBER_COOKIE_DURATION", COOKIE_DURATION)
+
+ # prepare data
+ data = encode_cookie(str(session["_user_id"]))
+
+ if isinstance(duration, int):
+ duration = timedelta(seconds=duration)
+
+ try:
+ expires = datetime.utcnow() + duration
+ except TypeError as e:
+ raise Exception(
+ "REMEMBER_COOKIE_DURATION must be a datetime.timedelta,"
+ f" instead got: {duration}"
+ ) from e
+
+ # actually set it
+ response.set_cookie(
+ cookie_name,
+ value=data,
+ expires=expires,
+ domain=domain,
+ path=path,
+ secure=secure,
+ httponly=httponly,
+ samesite=samesite,
+ )
+
+ def _clear_cookie(self, response):
+ config = current_app.config
+ cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
+ domain = config.get("REMEMBER_COOKIE_DOMAIN")
+ path = config.get("REMEMBER_COOKIE_PATH", "/")
+ response.delete_cookie(cookie_name, domain=domain, path=path)
+
+ @property
+ def _login_disabled(self):
+ """Legacy property, use app.config['LOGIN_DISABLED'] instead."""
+ import warnings
+
+ warnings.warn(
+ "'_login_disabled' is deprecated and will be removed in"
+ " Flask-Login 0.7. Use 'LOGIN_DISABLED' in 'app.config'"
+ " instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ if has_app_context():
+ return current_app.config.get("LOGIN_DISABLED", False)
+ return False
+
+ @_login_disabled.setter
+ def _login_disabled(self, newvalue):
+ """Legacy property setter, use app.config['LOGIN_DISABLED'] instead."""
+ import warnings
+
+ warnings.warn(
+ "'_login_disabled' is deprecated and will be removed in"
+ " Flask-Login 0.7. Use 'LOGIN_DISABLED' in 'app.config'"
+ " instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ current_app.config["LOGIN_DISABLED"] = newvalue
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/mixins.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/mixins.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b3a71bbee1a6ad2b3f049f30f8f97004d769367
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/mixins.py
@@ -0,0 +1,65 @@
+class UserMixin:
+ """
+ This provides default implementations for the methods that Flask-Login
+ expects user objects to have.
+ """
+
+ # Python 3 implicitly set __hash__ to None if we override __eq__
+ # We set it back to its default implementation
+ __hash__ = object.__hash__
+
+ @property
+ def is_active(self):
+ return True
+
+ @property
+ def is_authenticated(self):
+ return self.is_active
+
+ @property
+ def is_anonymous(self):
+ return False
+
+ def get_id(self):
+ try:
+ return str(self.id)
+ except AttributeError:
+ raise NotImplementedError("No `id` attribute - override `get_id`") from None
+
+ def __eq__(self, other):
+ """
+ Checks the equality of two `UserMixin` objects using `get_id`.
+ """
+ if isinstance(other, UserMixin):
+ return self.get_id() == other.get_id()
+ return NotImplemented
+
+ def __ne__(self, other):
+ """
+ Checks the inequality of two `UserMixin` objects using `get_id`.
+ """
+ equal = self.__eq__(other)
+ if equal is NotImplemented:
+ return NotImplemented
+ return not equal
+
+
+class AnonymousUserMixin:
+ """
+ This is the default object for representing an anonymous user.
+ """
+
+ @property
+ def is_authenticated(self):
+ return False
+
+ @property
+ def is_active(self):
+ return False
+
+ @property
+ def is_anonymous(self):
+ return True
+
+ def get_id(self):
+ return
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/signals.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/signals.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf9157f8b80120b06ce411c5b7085920aa34b174
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/signals.py
@@ -0,0 +1,61 @@
+from flask.signals import Namespace
+
+_signals = Namespace()
+
+#: Sent when a user is logged in. In addition to the app (which is the
+#: sender), it is passed `user`, which is the user being logged in.
+user_logged_in = _signals.signal("logged-in")
+
+#: Sent when a user is logged out. In addition to the app (which is the
+#: sender), it is passed `user`, which is the user being logged out.
+user_logged_out = _signals.signal("logged-out")
+
+#: Sent when the user is loaded from the cookie. In addition to the app (which
+#: is the sender), it is passed `user`, which is the user being reloaded.
+user_loaded_from_cookie = _signals.signal("loaded-from-cookie")
+
+#: Sent when the user is loaded from the header. In addition to the app (which
+#: is the #: sender), it is passed `user`, which is the user being reloaded.
+_user_loaded_from_header = _signals.signal("loaded-from-header")
+
+#: Sent when the user is loaded from the request. In addition to the app (which
+#: is the #: sender), it is passed `user`, which is the user being reloaded.
+user_loaded_from_request = _signals.signal("loaded-from-request")
+
+#: Sent when a user's login is confirmed, marking it as fresh. (It is not
+#: called for a normal login.)
+#: It receives no additional arguments besides the app.
+user_login_confirmed = _signals.signal("login-confirmed")
+
+#: Sent when the `unauthorized` method is called on a `LoginManager`. It
+#: receives no additional arguments besides the app.
+user_unauthorized = _signals.signal("unauthorized")
+
+#: Sent when the `needs_refresh` method is called on a `LoginManager`. It
+#: receives no additional arguments besides the app.
+user_needs_refresh = _signals.signal("needs-refresh")
+
+#: Sent whenever the user is accessed/loaded
+#: receives no additional arguments besides the app.
+user_accessed = _signals.signal("accessed")
+
+#: Sent whenever session protection takes effect, and a session is either
+#: marked non-fresh or deleted. It receives no additional arguments besides
+#: the app.
+session_protected = _signals.signal("session-protected")
+
+
+def __getattr__(name):
+ if name == "user_loaded_from_header":
+ import warnings
+
+ warnings.warn(
+ "'user_loaded_from_header' is deprecated and will be"
+ " removed in Flask-Login 0.7. Use"
+ " 'user_loaded_from_request' instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _user_loaded_from_header
+
+ raise AttributeError(name)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/test_client.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/test_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..be2a8bf6ab7541aca05035cbaa03497b7007b6d8
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/test_client.py
@@ -0,0 +1,19 @@
+from flask.testing import FlaskClient
+
+
+class FlaskLoginClient(FlaskClient):
+ """
+ A Flask test client that knows how to log in users
+ using the Flask-Login extension.
+ """
+
+ def __init__(self, *args, **kwargs):
+ user = kwargs.pop("user", None)
+ fresh = kwargs.pop("fresh_login", True)
+
+ super().__init__(*args, **kwargs)
+
+ if user:
+ with self.session_transaction() as sess:
+ sess["_user_id"] = user.get_id()
+ sess["_fresh"] = fresh
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/utils.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..37b20564f2469fbb188afcd61c4eaeb0610e5151
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_login/utils.py
@@ -0,0 +1,415 @@
+import hmac
+from functools import wraps
+from hashlib import sha512
+from urllib.parse import parse_qs
+from urllib.parse import urlencode
+from urllib.parse import urlsplit
+from urllib.parse import urlunsplit
+
+from flask import current_app
+from flask import g
+from flask import has_request_context
+from flask import request
+from flask import session
+from flask import url_for
+from werkzeug.local import LocalProxy
+
+from .config import COOKIE_NAME
+from .config import EXEMPT_METHODS
+from .signals import user_logged_in
+from .signals import user_logged_out
+from .signals import user_login_confirmed
+
+#: A proxy for the current user. If no user is logged in, this will be an
+#: anonymous user
+current_user = LocalProxy(lambda: _get_user())
+
+
+def encode_cookie(payload, key=None):
+ """
+ This will encode a ``str`` value into a cookie, and sign that cookie
+ with the app's secret key.
+
+ :param payload: The value to encode, as `str`.
+ :type payload: str
+
+ :param key: The key to use when creating the cookie digest. If not
+ specified, the SECRET_KEY value from app config will be used.
+ :type key: str
+ """
+ return f"{payload}|{_cookie_digest(payload, key=key)}"
+
+
+def decode_cookie(cookie, key=None):
+ """
+ This decodes a cookie given by `encode_cookie`. If verification of the
+ cookie fails, ``None`` will be implicitly returned.
+
+ :param cookie: An encoded cookie.
+ :type cookie: str
+
+ :param key: The key to use when creating the cookie digest. If not
+ specified, the SECRET_KEY value from app config will be used.
+ :type key: str
+ """
+ try:
+ payload, digest = cookie.rsplit("|", 1)
+ if hasattr(digest, "decode"):
+ digest = digest.decode("ascii") # pragma: no cover
+ except ValueError:
+ return
+
+ if hmac.compare_digest(_cookie_digest(payload, key=key), digest):
+ return payload
+
+
+def make_next_param(login_url, current_url):
+ """
+ Reduces the scheme and host from a given URL so it can be passed to
+ the given `login` URL more efficiently.
+
+ :param login_url: The login URL being redirected to.
+ :type login_url: str
+ :param current_url: The URL to reduce.
+ :type current_url: str
+ """
+ l_url = urlsplit(login_url)
+ c_url = urlsplit(current_url)
+
+ if (not l_url.scheme or l_url.scheme == c_url.scheme) and (
+ not l_url.netloc or l_url.netloc == c_url.netloc
+ ):
+ return urlunsplit(("", "", c_url.path, c_url.query, ""))
+ return current_url
+
+
+def expand_login_view(login_view):
+ """
+ Returns the url for the login view, expanding the view name to a url if
+ needed.
+
+ :param login_view: The name of the login view or a URL for the login view.
+ :type login_view: str
+ """
+ if login_view.startswith(("https://", "http://", "/")):
+ return login_view
+
+ return url_for(login_view)
+
+
+def login_url(login_view, next_url=None, next_field="next"):
+ """
+ Creates a URL for redirecting to a login page. If only `login_view` is
+ provided, this will just return the URL for it. If `next_url` is provided,
+ however, this will append a ``next=URL`` parameter to the query string
+ so that the login view can redirect back to that URL. Flask-Login's default
+ unauthorized handler uses this function when redirecting to your login url.
+ To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This
+ prevents from redirecting to external sites if request headers Host or
+ X-Forwarded-For are present.
+
+ :param login_view: The name of the login view. (Alternately, the actual
+ URL to the login view.)
+ :type login_view: str
+ :param next_url: The URL to give the login view for redirection.
+ :type next_url: str
+ :param next_field: What field to store the next URL in. (It defaults to
+ ``next``.)
+ :type next_field: str
+ """
+ base = expand_login_view(login_view)
+
+ if next_url is None:
+ return base
+
+ parsed_result = urlsplit(base)
+ md = parse_qs(parsed_result.query, keep_blank_values=True)
+ md[next_field] = make_next_param(base, next_url)
+ netloc = current_app.config.get("FORCE_HOST_FOR_REDIRECTS") or parsed_result.netloc
+ parsed_result = parsed_result._replace(
+ netloc=netloc, query=urlencode(md, doseq=True)
+ )
+ return urlunsplit(parsed_result)
+
+
+def login_fresh():
+ """
+ This returns ``True`` if the current login is fresh.
+ """
+ return session.get("_fresh", False)
+
+
+def login_remembered():
+ """
+ This returns ``True`` if the current login is remembered across sessions.
+ """
+ config = current_app.config
+ cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
+ has_cookie = cookie_name in request.cookies and session.get("_remember") != "clear"
+ if has_cookie:
+ cookie = request.cookies[cookie_name]
+ user_id = decode_cookie(cookie)
+ return user_id is not None
+ return False
+
+
+def login_user(user, remember=False, duration=None, force=False, fresh=True):
+ """
+ Logs a user in. You should pass the actual user object to this. If the
+ user's `is_active` property is ``False``, they will not be logged in
+ unless `force` is ``True``.
+
+ This will return ``True`` if the log in attempt succeeds, and ``False`` if
+ it fails (i.e. because the user is inactive).
+
+ :param user: The user object to log in.
+ :type user: object
+ :param remember: Whether to remember the user after their session expires.
+ Defaults to ``False``.
+ :type remember: bool
+ :param duration: The amount of time before the remember cookie expires. If
+ ``None`` the value set in the settings is used. Defaults to ``None``.
+ :type duration: :class:`datetime.timedelta`
+ :param force: If the user is inactive, setting this to ``True`` will log
+ them in regardless. Defaults to ``False``.
+ :type force: bool
+ :param fresh: setting this to ``False`` will log in the user with a session
+ marked as not "fresh". Defaults to ``True``.
+ :type fresh: bool
+ """
+ if not force and not user.is_active:
+ return False
+
+ user_id = getattr(user, current_app.login_manager.id_attribute)()
+ session["_user_id"] = user_id
+ session["_fresh"] = fresh
+ session["_id"] = current_app.login_manager._session_identifier_generator()
+
+ if remember:
+ session["_remember"] = "set"
+ if duration is not None:
+ try:
+ # equal to timedelta.total_seconds() but works with Python 2.6
+ session["_remember_seconds"] = (
+ duration.microseconds
+ + (duration.seconds + duration.days * 24 * 3600) * 10**6
+ ) / 10.0**6
+ except AttributeError as e:
+ raise Exception(
+ f"duration must be a datetime.timedelta, instead got: {duration}"
+ ) from e
+
+ current_app.login_manager._update_request_context_with_user(user)
+ user_logged_in.send(current_app._get_current_object(), user=_get_user())
+ return True
+
+
+def logout_user():
+ """
+ Logs a user out. (You do not need to pass the actual user.) This will
+ also clean up the remember me cookie if it exists.
+ """
+
+ user = _get_user()
+
+ if "_user_id" in session:
+ session.pop("_user_id")
+
+ if "_fresh" in session:
+ session.pop("_fresh")
+
+ if "_id" in session:
+ session.pop("_id")
+
+ cookie_name = current_app.config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
+ if cookie_name in request.cookies:
+ session["_remember"] = "clear"
+ if "_remember_seconds" in session:
+ session.pop("_remember_seconds")
+
+ user_logged_out.send(current_app._get_current_object(), user=user)
+
+ current_app.login_manager._update_request_context_with_user()
+ return True
+
+
+def confirm_login():
+ """
+ This sets the current session as fresh. Sessions become stale when they
+ are reloaded from a cookie.
+ """
+ session["_fresh"] = True
+ session["_id"] = current_app.login_manager._session_identifier_generator()
+ user_login_confirmed.send(current_app._get_current_object())
+
+
+def login_required(func):
+ """
+ If you decorate a view with this, it will ensure that the current user is
+ logged in and authenticated before calling the actual view. (If they are
+ not, it calls the :attr:`LoginManager.unauthorized` callback.) For
+ example::
+
+ @app.route('/post')
+ @login_required
+ def post():
+ pass
+
+ If there are only certain times you need to require that your user is
+ logged in, you can do so with::
+
+ if not current_user.is_authenticated:
+ return current_app.login_manager.unauthorized()
+
+ ...which is essentially the code that this function adds to your views.
+
+ It can be convenient to globally turn off authentication when unit testing.
+ To enable this, if the application configuration variable `LOGIN_DISABLED`
+ is set to `True`, this decorator will be ignored.
+
+ .. Note ::
+
+ Per `W3 guidelines for CORS preflight requests
+ `_,
+ HTTP ``OPTIONS`` requests are exempt from login checks.
+
+ :param func: The view function to decorate.
+ :type func: function
+ """
+
+ @wraps(func)
+ def decorated_view(*args, **kwargs):
+ if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
+ pass
+ elif not current_user.is_authenticated:
+ return current_app.login_manager.unauthorized()
+
+ # flask 1.x compatibility
+ # current_app.ensure_sync is only available in Flask >= 2.0
+ if callable(getattr(current_app, "ensure_sync", None)):
+ return current_app.ensure_sync(func)(*args, **kwargs)
+ return func(*args, **kwargs)
+
+ return decorated_view
+
+
+def fresh_login_required(func):
+ """
+ If you decorate a view with this, it will ensure that the current user's
+ login is fresh - i.e. their session was not restored from a 'remember me'
+ cookie. Sensitive operations, like changing a password or e-mail, should
+ be protected with this, to impede the efforts of cookie thieves.
+
+ If the user is not authenticated, :meth:`LoginManager.unauthorized` is
+ called as normal. If they are authenticated, but their session is not
+ fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that
+ case, you will need to provide a :attr:`LoginManager.refresh_view`.)
+
+ Behaves identically to the :func:`login_required` decorator with respect
+ to configuration variables.
+
+ .. Note ::
+
+ Per `W3 guidelines for CORS preflight requests
+ `_,
+ HTTP ``OPTIONS`` requests are exempt from login checks.
+
+ :param func: The view function to decorate.
+ :type func: function
+ """
+
+ @wraps(func)
+ def decorated_view(*args, **kwargs):
+ if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
+ pass
+ elif not current_user.is_authenticated:
+ return current_app.login_manager.unauthorized()
+ elif not login_fresh():
+ return current_app.login_manager.needs_refresh()
+ try:
+ # current_app.ensure_sync available in Flask >= 2.0
+ return current_app.ensure_sync(func)(*args, **kwargs)
+ except AttributeError: # pragma: no cover
+ return func(*args, **kwargs)
+
+ return decorated_view
+
+
+def set_login_view(login_view, blueprint=None):
+ """
+ Sets the login view for the app or blueprint. If a blueprint is passed,
+ the login view is set for this blueprint on ``blueprint_login_views``.
+
+ :param login_view: The user object to log in.
+ :type login_view: str
+ :param blueprint: The blueprint which this login view should be set on.
+ Defaults to ``None``.
+ :type blueprint: object
+ """
+
+ num_login_views = len(current_app.login_manager.blueprint_login_views)
+ if blueprint is not None or num_login_views != 0:
+ (current_app.login_manager.blueprint_login_views[blueprint.name]) = login_view
+
+ if (
+ current_app.login_manager.login_view is not None
+ and None not in current_app.login_manager.blueprint_login_views
+ ):
+ (
+ current_app.login_manager.blueprint_login_views[None]
+ ) = current_app.login_manager.login_view
+
+ current_app.login_manager.login_view = None
+ else:
+ current_app.login_manager.login_view = login_view
+
+
+def _get_user():
+ if has_request_context():
+ if "_login_user" not in g:
+ current_app.login_manager._load_user()
+
+ return g._login_user
+
+ return None
+
+
+def _cookie_digest(payload, key=None):
+ key = _secret_key(key)
+
+ return hmac.new(key, payload.encode("utf-8"), sha512).hexdigest()
+
+
+def _get_remote_addr():
+ address = request.headers.get("X-Forwarded-For", request.remote_addr)
+ if address is not None:
+ # An 'X-Forwarded-For' header includes a comma separated list of the
+ # addresses, the first address being the actual remote address.
+ address = address.encode("utf-8").split(b",")[0].strip()
+ return address
+
+
+def _create_identifier():
+ user_agent = request.headers.get("User-Agent")
+ if user_agent is not None:
+ user_agent = user_agent.encode("utf-8")
+ base = f"{_get_remote_addr()}|{user_agent}"
+ if str is bytes:
+ base = str(base, "utf-8", errors="replace") # pragma: no cover
+ h = sha512()
+ h.update(base.encode("utf8"))
+ return h.hexdigest()
+
+
+def _user_context_processor():
+ return dict(current_user=_get_user())
+
+
+def _secret_key(key=None):
+ if key is None:
+ key = current_app.config["SECRET_KEY"]
+
+ if isinstance(key, str): # pragma: no cover
+ key = key.encode("latin1") # ensure bytes
+
+ return key
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_migrate/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_migrate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..197f17bdab6bc0c820052d34d7943d9c0eb8af2d
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_migrate/__init__.py
@@ -0,0 +1,266 @@
+import argparse
+from functools import wraps
+import logging
+import os
+import sys
+from flask import current_app, g
+from alembic import __version__ as __alembic_version__
+from alembic.config import Config as AlembicConfig
+from alembic import command
+from alembic.util import CommandError
+
+alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]])
+log = logging.getLogger(__name__)
+
+
+class _MigrateConfig(object):
+ def __init__(self, migrate, db, **kwargs):
+ self.migrate = migrate
+ self.db = db
+ self.directory = migrate.directory
+ self.configure_args = kwargs
+
+ @property
+ def metadata(self):
+ """
+ Backwards compatibility, in old releases app.extensions['migrate']
+ was set to db, and env.py accessed app.extensions['migrate'].metadata
+ """
+ return self.db.metadata
+
+
+class Config(AlembicConfig):
+ def __init__(self, *args, **kwargs):
+ self.template_directory = kwargs.pop('template_directory', None)
+ super().__init__(*args, **kwargs)
+
+ def get_template_directory(self):
+ if self.template_directory:
+ return self.template_directory
+ package_dir = os.path.abspath(os.path.dirname(__file__))
+ return os.path.join(package_dir, 'templates')
+
+
+class Migrate(object):
+ def __init__(self, app=None, db=None, directory='migrations', command='db',
+ compare_type=True, render_as_batch=True, **kwargs):
+ self.configure_callbacks = []
+ self.db = db
+ self.command = command
+ self.directory = str(directory)
+ self.alembic_ctx_kwargs = kwargs
+ self.alembic_ctx_kwargs['compare_type'] = compare_type
+ self.alembic_ctx_kwargs['render_as_batch'] = render_as_batch
+ if app is not None and db is not None:
+ self.init_app(app, db, directory)
+
+ def init_app(self, app, db=None, directory=None, command=None,
+ compare_type=None, render_as_batch=None, **kwargs):
+ self.db = db or self.db
+ self.command = command or self.command
+ self.directory = str(directory or self.directory)
+ self.alembic_ctx_kwargs.update(kwargs)
+ if compare_type is not None:
+ self.alembic_ctx_kwargs['compare_type'] = compare_type
+ if render_as_batch is not None:
+ self.alembic_ctx_kwargs['render_as_batch'] = render_as_batch
+ if not hasattr(app, 'extensions'):
+ app.extensions = {}
+ app.extensions['migrate'] = _MigrateConfig(
+ self, self.db, **self.alembic_ctx_kwargs)
+
+ from flask_migrate.cli import db as db_cli_group
+ app.cli.add_command(db_cli_group, name=self.command)
+
+ def configure(self, f):
+ self.configure_callbacks.append(f)
+ return f
+
+ def call_configure_callbacks(self, config):
+ for f in self.configure_callbacks:
+ config = f(config)
+ return config
+
+ def get_config(self, directory=None, x_arg=None, opts=None):
+ if directory is None:
+ directory = self.directory
+ directory = str(directory)
+ config = Config(os.path.join(directory, 'alembic.ini'))
+ config.set_main_option('script_location', directory)
+ if config.cmd_opts is None:
+ config.cmd_opts = argparse.Namespace()
+ for opt in opts or []:
+ setattr(config.cmd_opts, opt, True)
+ if not hasattr(config.cmd_opts, 'x'):
+ setattr(config.cmd_opts, 'x', [])
+ for x in getattr(g, 'x_arg', []):
+ config.cmd_opts.x.append(x)
+ if x_arg is not None:
+ if isinstance(x_arg, list) or isinstance(x_arg, tuple):
+ for x in x_arg:
+ config.cmd_opts.x.append(x)
+ else:
+ config.cmd_opts.x.append(x_arg)
+ return self.call_configure_callbacks(config)
+
+
+def catch_errors(f):
+ @wraps(f)
+ def wrapped(*args, **kwargs):
+ try:
+ f(*args, **kwargs)
+ except (CommandError, RuntimeError) as exc:
+ log.error('Error: ' + str(exc))
+ sys.exit(1)
+ return wrapped
+
+
+@catch_errors
+def list_templates():
+ """List available templates."""
+ config = Config()
+ config.print_stdout("Available templates:\n")
+ for tempname in sorted(os.listdir(config.get_template_directory())):
+ with open(
+ os.path.join(config.get_template_directory(), tempname, "README")
+ ) as readme:
+ synopsis = next(readme).strip()
+ config.print_stdout("%s - %s", tempname, synopsis)
+
+
+@catch_errors
+def init(directory=None, multidb=False, template=None, package=False):
+ """Creates a new migration repository"""
+ if directory is None:
+ directory = current_app.extensions['migrate'].directory
+ template_directory = None
+ if template is not None and ('/' in template or '\\' in template):
+ template_directory, template = os.path.split(template)
+ config = Config(template_directory=template_directory)
+ config.set_main_option('script_location', directory)
+ config.config_file_name = os.path.join(directory, 'alembic.ini')
+ config = current_app.extensions['migrate'].\
+ migrate.call_configure_callbacks(config)
+ if multidb and template is None:
+ template = 'flask-multidb'
+ elif template is None:
+ template = 'flask'
+ command.init(config, directory, template=template, package=package)
+
+
+@catch_errors
+def revision(directory=None, message=None, autogenerate=False, sql=False,
+ head='head', splice=False, branch_label=None, version_path=None,
+ rev_id=None):
+ """Create a new revision file."""
+ opts = ['autogenerate'] if autogenerate else None
+ config = current_app.extensions['migrate'].migrate.get_config(
+ directory, opts=opts)
+ command.revision(config, message, autogenerate=autogenerate, sql=sql,
+ head=head, splice=splice, branch_label=branch_label,
+ version_path=version_path, rev_id=rev_id)
+
+
+@catch_errors
+def migrate(directory=None, message=None, sql=False, head='head', splice=False,
+ branch_label=None, version_path=None, rev_id=None, x_arg=None):
+ """Alias for 'revision --autogenerate'"""
+ config = current_app.extensions['migrate'].migrate.get_config(
+ directory, opts=['autogenerate'], x_arg=x_arg)
+ command.revision(config, message, autogenerate=True, sql=sql,
+ head=head, splice=splice, branch_label=branch_label,
+ version_path=version_path, rev_id=rev_id)
+
+
+@catch_errors
+def edit(directory=None, revision='current'):
+ """Edit current revision."""
+ if alembic_version >= (0, 8, 0):
+ config = current_app.extensions['migrate'].migrate.get_config(
+ directory)
+ command.edit(config, revision)
+ else:
+ raise RuntimeError('Alembic 0.8.0 or greater is required')
+
+
+@catch_errors
+def merge(directory=None, revisions='', message=None, branch_label=None,
+ rev_id=None):
+ """Merge two revisions together. Creates a new migration file"""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ command.merge(config, revisions, message=message,
+ branch_label=branch_label, rev_id=rev_id)
+
+
+@catch_errors
+def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None):
+ """Upgrade to a later version"""
+ config = current_app.extensions['migrate'].migrate.get_config(directory,
+ x_arg=x_arg)
+ command.upgrade(config, revision, sql=sql, tag=tag)
+
+
+@catch_errors
+def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None):
+ """Revert to a previous version"""
+ config = current_app.extensions['migrate'].migrate.get_config(directory,
+ x_arg=x_arg)
+ if sql and revision == '-1':
+ revision = 'head:-1'
+ command.downgrade(config, revision, sql=sql, tag=tag)
+
+
+@catch_errors
+def show(directory=None, revision='head'):
+ """Show the revision denoted by the given symbol."""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ command.show(config, revision)
+
+
+@catch_errors
+def history(directory=None, rev_range=None, verbose=False,
+ indicate_current=False):
+ """List changeset scripts in chronological order."""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ if alembic_version >= (0, 9, 9):
+ command.history(config, rev_range, verbose=verbose,
+ indicate_current=indicate_current)
+ else:
+ command.history(config, rev_range, verbose=verbose)
+
+
+@catch_errors
+def heads(directory=None, verbose=False, resolve_dependencies=False):
+ """Show current available heads in the script directory"""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ command.heads(config, verbose=verbose,
+ resolve_dependencies=resolve_dependencies)
+
+
+@catch_errors
+def branches(directory=None, verbose=False):
+ """Show current branch points"""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ command.branches(config, verbose=verbose)
+
+
+@catch_errors
+def current(directory=None, verbose=False):
+ """Display the current revision for each database."""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ command.current(config, verbose=verbose)
+
+
+@catch_errors
+def stamp(directory=None, revision='head', sql=False, tag=None, purge=False):
+ """'stamp' the revision table with the given revision; don't run any
+ migrations"""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ command.stamp(config, revision, sql=sql, tag=tag, purge=purge)
+
+
+@catch_errors
+def check(directory=None):
+ """Check if there are any new operations to migrate"""
+ config = current_app.extensions['migrate'].migrate.get_config(directory)
+ command.check(config)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_migrate/cli.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_migrate/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..73a31ba6dff79f0b9880e0fe2e5fe3714967135a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_migrate/cli.py
@@ -0,0 +1,258 @@
+import click
+from flask import g
+from flask.cli import with_appcontext
+from flask_migrate import list_templates as _list_templates
+from flask_migrate import init as _init
+from flask_migrate import revision as _revision
+from flask_migrate import migrate as _migrate
+from flask_migrate import edit as _edit
+from flask_migrate import merge as _merge
+from flask_migrate import upgrade as _upgrade
+from flask_migrate import downgrade as _downgrade
+from flask_migrate import show as _show
+from flask_migrate import history as _history
+from flask_migrate import heads as _heads
+from flask_migrate import branches as _branches
+from flask_migrate import current as _current
+from flask_migrate import stamp as _stamp
+from flask_migrate import check as _check
+
+
+@click.group()
+@click.option('-x', '--x-arg', multiple=True,
+ help='Additional arguments consumed by custom env.py scripts')
+@with_appcontext
+def db(x_arg):
+ """Perform database migrations."""
+ g.x_arg = x_arg # these will be picked up by Migrate.get_config()
+
+
+@db.command()
+@with_appcontext
+def list_templates():
+ """List available templates."""
+ _list_templates()
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('--multidb', is_flag=True,
+ help=('Support multiple databases'))
+@click.option('-t', '--template', default=None,
+ help=('Repository template to use (default is "flask")'))
+@click.option('--package', is_flag=True,
+ help=('Write empty __init__.py files to the environment and '
+ 'version locations'))
+@with_appcontext
+def init(directory, multidb, template, package):
+ """Creates a new migration repository."""
+ _init(directory, multidb, template, package)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('-m', '--message', default=None, help='Revision message')
+@click.option('--autogenerate', is_flag=True,
+ help=('Populate revision script with candidate migration '
+ 'operations, based on comparison of database to model'))
+@click.option('--sql', is_flag=True,
+ help=('Don\'t emit SQL to database - dump to standard output '
+ 'instead'))
+@click.option('--head', default='head',
+ help=('Specify head revision or @head to base new '
+ 'revision on'))
+@click.option('--splice', is_flag=True,
+ help=('Allow a non-head revision as the "head" to splice onto'))
+@click.option('--branch-label', default=None,
+ help=('Specify a branch label to apply to the new revision'))
+@click.option('--version-path', default=None,
+ help=('Specify specific path from config for version file'))
+@click.option('--rev-id', default=None,
+ help=('Specify a hardcoded revision id instead of generating '
+ 'one'))
+@with_appcontext
+def revision(directory, message, autogenerate, sql, head, splice, branch_label,
+ version_path, rev_id):
+ """Create a new revision file."""
+ _revision(directory, message, autogenerate, sql, head, splice,
+ branch_label, version_path, rev_id)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('-m', '--message', default=None, help='Revision message')
+@click.option('--sql', is_flag=True,
+ help=('Don\'t emit SQL to database - dump to standard output '
+ 'instead'))
+@click.option('--head', default='head',
+ help=('Specify head revision or @head to base new '
+ 'revision on'))
+@click.option('--splice', is_flag=True,
+ help=('Allow a non-head revision as the "head" to splice onto'))
+@click.option('--branch-label', default=None,
+ help=('Specify a branch label to apply to the new revision'))
+@click.option('--version-path', default=None,
+ help=('Specify specific path from config for version file'))
+@click.option('--rev-id', default=None,
+ help=('Specify a hardcoded revision id instead of generating '
+ 'one'))
+@click.option('-x', '--x-arg', multiple=True,
+ help='Additional arguments consumed by custom env.py scripts')
+@with_appcontext
+def migrate(directory, message, sql, head, splice, branch_label, version_path,
+ rev_id, x_arg):
+ """Autogenerate a new revision file (Alias for
+ 'revision --autogenerate')"""
+ _migrate(directory, message, sql, head, splice, branch_label, version_path,
+ rev_id, x_arg)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.argument('revision', default='head')
+@with_appcontext
+def edit(directory, revision):
+ """Edit a revision file"""
+ _edit(directory, revision)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('-m', '--message', default=None, help='Merge revision message')
+@click.option('--branch-label', default=None,
+ help=('Specify a branch label to apply to the new revision'))
+@click.option('--rev-id', default=None,
+ help=('Specify a hardcoded revision id instead of generating '
+ 'one'))
+@click.argument('revisions', nargs=-1)
+@with_appcontext
+def merge(directory, message, branch_label, rev_id, revisions):
+ """Merge two revisions together, creating a new revision file"""
+ _merge(directory, revisions, message, branch_label, rev_id)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('--sql', is_flag=True,
+ help=('Don\'t emit SQL to database - dump to standard output '
+ 'instead'))
+@click.option('--tag', default=None,
+ help=('Arbitrary "tag" name - can be used by custom env.py '
+ 'scripts'))
+@click.option('-x', '--x-arg', multiple=True,
+ help='Additional arguments consumed by custom env.py scripts')
+@click.argument('revision', default='head')
+@with_appcontext
+def upgrade(directory, sql, tag, x_arg, revision):
+ """Upgrade to a later version"""
+ _upgrade(directory, revision, sql, tag, x_arg)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('--sql', is_flag=True,
+ help=('Don\'t emit SQL to database - dump to standard output '
+ 'instead'))
+@click.option('--tag', default=None,
+ help=('Arbitrary "tag" name - can be used by custom env.py '
+ 'scripts'))
+@click.option('-x', '--x-arg', multiple=True,
+ help='Additional arguments consumed by custom env.py scripts')
+@click.argument('revision', default='-1')
+@with_appcontext
+def downgrade(directory, sql, tag, x_arg, revision):
+ """Revert to a previous version"""
+ _downgrade(directory, revision, sql, tag, x_arg)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.argument('revision', default='head')
+@with_appcontext
+def show(directory, revision):
+ """Show the revision denoted by the given symbol."""
+ _show(directory, revision)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('-r', '--rev-range', default=None,
+ help='Specify a revision range; format is [start]:[end]')
+@click.option('-v', '--verbose', is_flag=True, help='Use more verbose output')
+@click.option('-i', '--indicate-current', is_flag=True,
+ help=('Indicate current version (Alembic 0.9.9 or greater is '
+ 'required)'))
+@with_appcontext
+def history(directory, rev_range, verbose, indicate_current):
+ """List changeset scripts in chronological order."""
+ _history(directory, rev_range, verbose, indicate_current)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('-v', '--verbose', is_flag=True, help='Use more verbose output')
+@click.option('--resolve-dependencies', is_flag=True,
+ help='Treat dependency versions as down revisions')
+@with_appcontext
+def heads(directory, verbose, resolve_dependencies):
+ """Show current available heads in the script directory"""
+ _heads(directory, verbose, resolve_dependencies)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('-v', '--verbose', is_flag=True, help='Use more verbose output')
+@with_appcontext
+def branches(directory, verbose):
+ """Show current branch points"""
+ _branches(directory, verbose)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('-v', '--verbose', is_flag=True, help='Use more verbose output')
+@with_appcontext
+def current(directory, verbose):
+ """Display the current revision for each database."""
+ _current(directory, verbose)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@click.option('--sql', is_flag=True,
+ help=('Don\'t emit SQL to database - dump to standard output '
+ 'instead'))
+@click.option('--tag', default=None,
+ help=('Arbitrary "tag" name - can be used by custom env.py '
+ 'scripts'))
+@click.option('--purge', is_flag=True,
+ help=('Delete the version in the alembic_version table before '
+ 'stamping'))
+@click.argument('revision', default='head')
+@with_appcontext
+def stamp(directory, sql, tag, revision, purge):
+ """'stamp' the revision table with the given revision; don't run any
+ migrations"""
+ _stamp(directory, revision, sql, tag, purge)
+
+
+@db.command()
+@click.option('-d', '--directory', default=None,
+ help=('Migration script directory (default is "migrations")'))
+@with_appcontext
+def check(directory):
+ """Check if there are any new operations to migrate"""
+ _check(directory)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_paranoid/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_paranoid/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3579ed455315f515cdc34782570b1c07f88c6d83
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_paranoid/__init__.py
@@ -0,0 +1 @@
+from .paranoid import Paranoid # noqa: F401
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_paranoid/paranoid.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_paranoid/paranoid.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae0f3686a1ea6b88d7ffde705d02d79623d24d3f
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_paranoid/paranoid.py
@@ -0,0 +1,113 @@
+from hashlib import sha256
+import sys
+
+from flask import session, request, make_response, url_for, current_app, \
+ redirect
+from werkzeug.exceptions import Unauthorized
+
+
+class Paranoid(object):
+ def __init__(self, app=None):
+ self.invalid_session_handler = self._default_invalid_session_handler
+ if app:
+ self.init_app(app)
+
+ def init_app(self, app):
+ @app.before_request
+ def before_request():
+ token = self.create_token()
+ existing_token = self.get_token_from_session()
+ if existing_token is None:
+ # this is a new session, so we write our id in it
+ self.write_token_to_session(token)
+ elif existing_token != token:
+ # this session is invalid, so we get rid of it
+ if callable(self.invalid_session_handler):
+ response = make_response(self.invalid_session_handler())
+ else:
+ if self.invalid_session_handler.startswith(
+ ('http://', 'https://', '/')):
+ url = self.invalid_session_handler
+ else:
+ url = url_for(self.invalid_session_handler)
+ response = redirect(url)
+ self.clear_session(response)
+ return response
+
+ def on_invalid_session(self, f):
+ self.invalid_session_handler = f
+ return f
+
+ def _default_invalid_session_handler(self):
+ try:
+ raise Unauthorized()
+ except Exception as e:
+ response = current_app.handle_user_exception(e)
+ return response
+
+ @property
+ def redirect_view(self):
+ return self.invalid_session_handler
+
+ @redirect_view.setter
+ def redirect_view(self, view):
+ self.invalid_session_handler = view
+
+ def _get_remote_addr(self):
+ address = request.headers.get('X-Forwarded-For', request.remote_addr)
+ if address is None: # pragma: no cover
+ address = 'x.x.x.x'
+ address = address.encode('utf-8').split(b',')[0].strip()
+ return address
+
+ def create_token(self):
+ """Create a session protection token for this client.
+
+ This method generates a session protection token for the cilent, which
+ consists in a hash of the user agent and the IP address. This method
+ can be overriden by subclasses to implement different token generation
+ algorithms.
+ """
+ user_agent = request.headers.get('User-Agent')
+ if user_agent is None: # pragma: no cover
+ user_agent = 'no user agent'
+ user_agent = user_agent.encode('utf-8')
+ base = self._get_remote_addr() + b'|' + user_agent
+ h = sha256()
+ h.update(base)
+ return h.hexdigest()
+
+ def get_token_from_session(self):
+ """Return the session protection token stored from the client session.
+
+ This method retrieves the stored session protection token, or None if
+ this is a brand new session that doesn't have a token in it. This
+ default implementation finds the token in the user session. Subclasses
+ can override this method and implement other storage methods.
+ """
+ return session.get('_paranoid_token')
+
+ def write_token_to_session(self, token):
+ """Write a session protection token to the client session.
+
+ This methods writes the session protection token. This default
+ implementation writes the token to the user session. Subclasses can
+ override this method to implement other storage methods.
+ """
+ session['_paranoid_token'] = token
+
+ def clear_session(self, response):
+ """Clear the session.
+
+ This method is invoked when the session is found to be invalid.
+ Subclasses can override this method to implement a custom session
+ reset.
+ """
+ session.clear()
+
+ # if flask-login is installed, we try to clear the
+ # "remember me" cookie, just in case it is set
+ if 'flask_login' in sys.modules:
+ remember_cookie = current_app.config.get('REMEMBER_COOKIE',
+ 'remember_token')
+ response.set_cookie(remember_cookie, '', expires=0, max_age=0)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/__init__.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..408a52a36d7e66767ba66b687b07ca3a57a4cd92
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/__init__.py
@@ -0,0 +1,139 @@
+"""
+ flask_security
+ ~~~~~~~~~~~~~~
+
+ Flask-Security is a Flask extension that aims to add comprehensive security
+ to Flask applications.
+
+ :copyright: (c) 2012-2019 by Matt Wright.
+ :copyright: (c) 2019-2024 by J. Christopher Wagner.
+ :license: MIT, see LICENSE for more details.
+"""
+
+# flake8: noqa: F401
+from .changeable import admin_change_password
+from .core import (
+ Security,
+ RoleMixin,
+ UserMixin,
+ WebAuthnMixin,
+ FormInfo,
+ current_user,
+)
+from .datastore import (
+ UserDatastore,
+ SQLAlchemyUserDatastore,
+ AsaList,
+ MongoEngineUserDatastore,
+ PeeweeUserDatastore,
+ PonyUserDatastore,
+ SQLAlchemySessionUserDatastore,
+)
+from .decorators import (
+ auth_token_required,
+ anonymous_user_required,
+ handle_csrf,
+ http_auth_required,
+ login_required,
+ roles_accepted,
+ roles_required,
+ auth_required,
+ permissions_accepted,
+ permissions_required,
+ unauth_csrf,
+)
+from .forms import (
+ Form,
+ ChangePasswordForm,
+ ForgotPasswordForm,
+ LoginForm,
+ RegisterForm,
+ ResetPasswordForm,
+ PasswordlessLoginForm,
+ ConfirmRegisterForm,
+ SendConfirmationForm,
+ TwoFactorRescueForm,
+ TwoFactorSetupForm,
+ TwoFactorVerifyCodeForm,
+ VerifyForm,
+ unique_identity_attribute,
+)
+from .mail_util import MailUtil, EmailValidateException
+from .oauth_glue import OAuthGlue
+from .oauth_provider import FsOAuthProvider
+from .password_util import PasswordUtil
+from .phone_util import PhoneUtil
+from .recovery_codes import (
+ MfRecoveryCodesUtil,
+ MfRecoveryForm,
+ MfRecoveryCodesForm,
+)
+from .signals import (
+ confirm_instructions_sent,
+ login_instructions_sent,
+ password_changed,
+ password_reset,
+ reset_password_instructions_sent,
+ tf_code_confirmed,
+ tf_profile_changed,
+ tf_security_token_sent,
+ tf_disabled,
+ user_authenticated,
+ user_unauthenticated,
+ user_confirmed,
+ user_registered,
+ user_not_registered,
+ us_security_token_sent,
+ us_profile_changed,
+ wan_deleted,
+ wan_registered,
+)
+from .totp import Totp
+from .twofactor import tf_send_security_token
+from .tf_plugin import TwoFactorSelectForm
+from .unified_signin import (
+ UnifiedSigninForm,
+ UnifiedSigninSetupForm,
+ UnifiedSigninSetupValidateForm,
+ UnifiedVerifyForm,
+ us_send_security_token,
+)
+from .username_util import UsernameUtil
+from .utils import (
+ SmsSenderBaseClass,
+ SmsSenderFactory,
+ check_and_get_token_status,
+ get_hmac,
+ get_request_attr,
+ get_token_status,
+ get_url,
+ hash_password,
+ check_and_update_authn_fresh,
+ login_user,
+ logout_user,
+ lookup_identity,
+ naive_utcnow,
+ password_breached_validator,
+ password_complexity_validator,
+ password_length_validator,
+ pwned,
+ send_mail,
+ transform_url,
+ uia_phone_mapper,
+ uia_email_mapper,
+ uia_username_mapper,
+ url_for_security,
+ verify_password,
+ verify_and_update_password,
+)
+from .webauthn import (
+ WebAuthnRegisterForm,
+ WebAuthnRegisterResponseForm,
+ WebAuthnSigninForm,
+ WebAuthnSigninResponseForm,
+ WebAuthnDeleteForm,
+ WebAuthnVerifyForm,
+)
+from .webauthn_util import WebauthnUtil
+
+__version__ = "5.4.3"
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/babel.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/babel.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f99e7984b3b3b346c6a880a0e58c48a7a7b961a
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/babel.py
@@ -0,0 +1,114 @@
+"""
+ flask_security.babel
+ ~~~~~~~~~~~~~~~~~~~~
+
+ I18N support for Flask-Security.
+
+ :copyright: (c) 2019-2023 by J. Christopher Wagner (jwag).
+ :license: MIT, see LICENSE for more details.
+
+ As of Flask-Babel 2.0.0 - it supports the Flask-BabelEx Domain extension - and it
+ is maintained. If that isn't installed fall back to a Null Domain
+"""
+
+# flake8: noqa: F811
+
+from collections.abc import Iterable
+import atexit
+from contextlib import ExitStack
+from importlib_resources import files, as_file
+
+from flask import current_app
+from .utils import config_value as cv
+
+
+def has_babel_ext():
+ # Has the application initialized the appropriate babel extension....
+ return current_app and "babel" in current_app.extensions
+
+
+try:
+ from flask_babel import Domain, get_locale
+ from babel.support import LazyProxy
+ from babel.lists import format_list
+
+ class FsDomain(Domain):
+ def __init__(self, app):
+ # By default, we use our packaged translations. However, we have to allow
+ # for app to add translation directories or completely override ours.
+ # Grabbing the packaged translations is a bit complex - so we use
+ # the keyword 'builtin' to mean ours.
+ cfdir = cv("I18N_DIRNAME", app=app)
+ if cfdir == "builtin" or (
+ isinstance(cfdir, Iterable) and "builtin" in cfdir
+ ):
+ fm = ExitStack()
+ atexit.register(fm.close)
+ ref = files("flask_security") / "translations"
+ path = fm.enter_context(as_file(ref))
+ if cfdir == "builtin":
+ dirs = [str(path)]
+ else:
+ dirs = [d if d != "builtin" else str(path) for d in cfdir]
+ else:
+ dirs = cfdir
+ super().__init__(
+ **{
+ "domain": cv("I18N_DOMAIN", app=app),
+ "translation_directories": dirs,
+ }
+ )
+
+ def gettext(self, string, **variables):
+ if not has_babel_ext():
+ return string if not variables else string % variables
+ return super().gettext(string, **variables)
+
+ def ngettext(self, singular, plural, num, **variables): # pragma: no cover
+ if not has_babel_ext():
+ variables.setdefault("num", num)
+ return (singular if num == 1 else plural) % variables
+ return super().ngettext(singular, plural, num, **variables)
+
+ @staticmethod
+ def format_list(lst, **kwargs):
+ # This is a Babel method
+ if not has_babel_ext():
+ return ", ".join(lst)
+ ll = get_locale()
+ return format_list(lst, locale=get_locale(), **kwargs)
+
+ def is_lazy_string(obj):
+ """Checks if the given object is a lazy string."""
+ return isinstance(obj, LazyProxy)
+
+ def make_lazy_string(__func, msg):
+ """Creates a lazy string by invoking func with args."""
+ return LazyProxy(__func, msg, enable_cache=False)
+
+except ImportError: # pragma: no cover
+ # Fake up just enough
+ class FsDomain: # type: ignore[no-redef]
+ def __init__(self, app):
+ pass
+
+ @staticmethod
+ def gettext(string, **variables):
+ return string if not variables else string % variables
+
+ @staticmethod
+ def ngettext(singular, plural, num, **variables):
+ variables.setdefault("num", num)
+ return (singular if num == 1 else plural) % variables
+
+ @staticmethod
+ def format_list(lst, **kwargs):
+ # This is a Babel method
+ if not has_babel_ext():
+ return ", ".join(lst)
+
+ def is_lazy_string(obj):
+ return False
+
+ def make_lazy_string(__func, msg):
+ return msg
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/changeable.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/changeable.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ec238471964740741e73649f3cc19fa3accc996
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/changeable.py
@@ -0,0 +1,90 @@
+"""
+ flask_security.changeable
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Flask-Security change password module
+
+ :copyright: (c) 2012 by Matt Wright.
+ :copyright: (c) 2019-2024 by J. Christopher Wagner (jwag).
+ :author: Eskil Heyn Olsen
+ :license: MIT, see LICENSE for more details.
+"""
+
+from __future__ import annotations
+
+import typing as t
+
+from flask import current_app, request, session
+from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME
+
+from .proxies import _datastore
+from .signals import password_changed
+from .utils import config_value as cv, hash_password, login_user, send_mail
+
+if t.TYPE_CHECKING: # pragma: no cover
+ from .datastore import User
+
+
+def send_password_changed_notice(user):
+ """Sends the password changed notice email for the specified user.
+
+ :param user: The user to send the notice to
+ """
+ if cv("SEND_PASSWORD_CHANGE_EMAIL"):
+ subject = cv("EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE")
+ send_mail(subject, user.email, "change_notice", user=user)
+
+
+def change_user_password(
+ user: User, password: str | None, notify: bool = True, autologin: bool = True
+) -> None:
+ """Change the specified user's password
+
+ :param user: The user object
+ :param password: The unhashed new password
+ :param notify: if True send notification (if configured) to user
+ :param autologin: if True, login user
+ """
+
+ if password:
+ user.password = hash_password(password)
+ else:
+ user.password = None
+ # Change uniquifier - this will cause ALL sessions to be invalidated.
+ _datastore.set_uniquifier(user)
+ _datastore.put(user)
+
+ if autologin:
+ # re-login user - this will update session, optional remember etc.
+ remember_cookie_name = current_app.config.get(
+ "REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME
+ )
+ has_remember_cookie = (
+ remember_cookie_name in request.cookies
+ and session.get("remember") != "clear"
+ )
+ login_user(user, remember=has_remember_cookie, authn_via=["change"])
+ if notify:
+ send_password_changed_notice(user)
+ password_changed.send(
+ current_app._get_current_object(), # type: ignore
+ _async_wrapper=current_app.ensure_sync,
+ user=user,
+ )
+
+
+def admin_change_password(user: User, new_passwd: str, notify: bool = True) -> None:
+ """
+ Administratively change a user's password.
+ Note that this will immediately render the user's existing sessions (and possibly
+ authentication tokens) invalid.
+
+ It is up to the caller to inform the user of their new password by some
+ out-of-band means.
+
+ :param user: The user object to change
+ :param new_passwd: The new plain-text password to assign to the user.
+ :param notify: If True and :py:data:`SECURITY_SEND_PASSWORD_CHANGE_EMAIL` is True
+ send the 'change_notice' email to the user.
+ """
+ change_user_password(user, new_passwd, notify=notify, autologin=False)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/cli.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..abe6b2648bfc88071687cd28bcd2092671d88581
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/cli.py
@@ -0,0 +1,352 @@
+"""
+ flask_security.cli
+ ~~~~~~~~~~~~~~~~~~
+
+ Command Line Interface for managing accounts and roles.
+
+ :copyright: (c) 2016 by CERN.
+ :copyright: (c) 2019-2022 by J. Christopher Wagner
+ :license: MIT, see LICENSE for more details.
+"""
+
+import functools
+
+import click
+from flask import current_app
+from werkzeug.local import LocalProxy
+from .quart_compat import get_quart_status
+
+from .changeable import admin_change_password
+from .forms import build_form
+from .utils import (
+ lookup_identity,
+ get_identity_attributes,
+ get_identity_attribute,
+ hash_password,
+)
+
+if get_quart_status(): # pragma: no cover
+ import quart.cli
+
+ # quart cli doesn't provide the with_appcontext function
+ def with_appcontext(f):
+ """Wraps a callback so that it's guaranteed to be executed with the
+ script's application context. If callbacks are registered directly
+ to the ``app.cli`` object then they are wrapped with this function
+ by default unless it's disabled.
+ """
+
+ @click.pass_context
+ def decorator(__ctx, *args, **kwargs):
+ with __ctx.ensure_object(quart.cli.ScriptInfo).load_app().app_context():
+ return __ctx.invoke(f, *args, **kwargs)
+
+ return functools.update_wrapper(decorator, f)
+
+else:
+ import flask.cli
+
+ with_appcontext = flask.cli.with_appcontext
+
+
+_security = LocalProxy(lambda: current_app.extensions["security"])
+_datastore = LocalProxy(lambda: current_app.extensions["security"].datastore)
+
+
+def commit(fn):
+ """Decorator to commit changes in datastore."""
+
+ @functools.wraps(fn)
+ def wrapper(*args, **kwargs):
+ fn(*args, **kwargs)
+ _datastore.commit()
+
+ return wrapper
+
+
+def fix_errors(form_errors):
+ # Form errors might have lazy text which normally would be processed by
+ # render_template
+ errors = {}
+ for k, v in form_errors.items():
+ errors[k] = [str(e) for e in v]
+ return errors
+
+
+@click.group()
+def users():
+ """User commands.
+
+ For commands that require a USER - pass in any identity attribute.
+ """
+
+
+@click.group()
+def roles():
+ """Role commands."""
+
+
+@users.command(
+ "create",
+ short_help=(
+ "Create a new user with one or more attributes using the syntax:"
+ " attr:value. If attr isn't set 'email' is presumed."
+ " Identity attribute values will be validated using the configured"
+ " confirm_register_form;"
+ " however, any ADDITIONAL attribute:value pairs will be sent to"
+ " datastore.create_user"
+ ),
+)
+@click.argument(
+ "attributes",
+ nargs=-1,
+)
+@click.password_option()
+@click.option("-a", "--active", default=False, is_flag=True)
+@with_appcontext
+@commit
+def users_create(attributes, password, active):
+ """Create a user."""
+ kwargs = {}
+
+ identity_attributes = get_identity_attributes()
+ for attrarg in attributes:
+ # If given identity is an identity_attribute - do a bit of pre-validating
+ # to provide nicer errors.
+ attr = "email"
+ if ":" in attrarg:
+ attr, attrarg = attrarg.split(":")
+ if attr in identity_attributes:
+ details = get_identity_attribute(attr)
+ idata = details["mapper"](attrarg)
+ if not idata:
+ raise click.UsageError(
+ f"Attr {attr} with value {attrarg} wasn't accepted by mapper"
+ )
+
+ kwargs[attr] = attrarg
+ kwargs.update(**{"password": password})
+
+ form = build_form("confirm_register_form", meta={"csrf": False}, **kwargs)
+
+ if form.validate():
+ # We don't use the form directly to provide values so that this CLI can actually
+ # set any usermodel attribute. We do grab email and password from the form
+ # so that we get any normalization results.
+ kwargs["password"] = hash_password(form.password.data)
+ kwargs["active"] = active
+ # echo normalized email...
+ if "email" in kwargs:
+ kwargs["email"] = form.email.data
+ _datastore.create_user(**kwargs)
+ click.secho("User created successfully.", fg="green")
+ kwargs["password"] = "****"
+ click.echo(kwargs)
+ else:
+ raise click.UsageError(f"Error creating user. {fix_errors(form.errors)}")
+
+
+@roles.command("create")
+@click.argument("name")
+@click.option("-d", "--description", default=None)
+@click.option("-p", "--permissions", help="A comma separated list")
+@with_appcontext
+@commit
+def roles_create(**kwargs):
+ """Create a role."""
+
+ # For some reason Click puts arguments in kwargs - even if they weren't specified.
+ if "permissions" in kwargs and not kwargs["permissions"]:
+ del kwargs["permissions"]
+ if "permissions" in kwargs and not hasattr(_datastore.role_model, "permissions"):
+ raise click.UsageError("Role model does not support permissions")
+ _datastore.create_role(**kwargs)
+ click.secho('Role "%(name)s" created successfully.' % kwargs, fg="green")
+
+
+@roles.command("add")
+@click.argument("user")
+@click.argument("role")
+@with_appcontext
+@commit
+def roles_add(user, role):
+ """Add role to user.
+
+ USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
+ """
+ user_obj = lookup_identity(user)
+ if user_obj is None:
+ raise click.UsageError("User not found.")
+
+ role = _datastore._prepare_role_modify_args(role)
+ if role is None:
+ raise click.UsageError("Cannot find role.")
+ if _datastore.add_role_to_user(user_obj, role):
+ click.secho(
+ f'Role "{role.name}" added to user "{user}" successfully.',
+ fg="green",
+ )
+ else:
+ raise click.UsageError("Cannot add role to user.")
+
+
+@roles.command("remove")
+@click.argument("user")
+@click.argument("role")
+@with_appcontext
+@commit
+def roles_remove(user, role):
+ """Remove role from user.
+
+ USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
+ """
+ user_obj = lookup_identity(user)
+ if user_obj is None:
+ raise click.UsageError("User not found.")
+
+ role = _datastore._prepare_role_modify_args(role)
+ if role is None:
+ raise click.UsageError("Cannot find role.")
+ if _datastore.remove_role_from_user(user_obj, role):
+ click.secho(
+ f'Role "{role.name}" removed from user "{user}" successfully.',
+ fg="green",
+ )
+ else:
+ raise click.UsageError("Cannot remove role from user.")
+
+
+@roles.command("add_permissions")
+@click.argument("role")
+@click.argument("permissions")
+@with_appcontext
+@commit
+def roles_add_permissions(role, permissions):
+ """Add permissions to role.
+
+ Role is an existing role name.
+ Permissions are a comma separated list.
+ """
+ role = _datastore._prepare_role_modify_args(role)
+ if role is None:
+ raise click.UsageError("Cannot find role.")
+ permlist = [s.strip() for s in permissions.split(",")]
+ if _datastore.add_permissions_to_role(role, permlist):
+ click.secho(
+ f'Permission(s) "{permissions}" added to role "{role.name}" successfully.',
+ fg="green",
+ )
+ else: # pragma: no cover
+ raise click.UsageError("Cannot add permission(s) to role.")
+
+
+@roles.command("remove_permissions")
+@click.argument("role")
+@click.argument("permissions")
+@with_appcontext
+@commit
+def roles_remove_permissions(role, permissions):
+ """Remove permissions from role.
+
+ Role is an existing role name.
+ Permissions are a comma separated list.
+ """
+ role = _datastore._prepare_role_modify_args(role)
+ if role is None:
+ raise click.UsageError("Cannot find role.")
+ permlist = [s.strip() for s in permissions.split(",")]
+ if _datastore.remove_permissions_from_role(role, permlist):
+ click.secho(
+ f'Permission(s) "{permissions}" removed from role'
+ f' "{role.name}" successfully.',
+ fg="green",
+ )
+ else: # pragma: no cover
+ raise click.UsageError("Cannot remove permission(s) from role.")
+
+
+@users.command("activate")
+@click.argument("user")
+@with_appcontext
+@commit
+def users_activate(user):
+ """Activate a user.
+
+ USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
+ """
+ user_obj = lookup_identity(user)
+ if user_obj is None:
+ raise click.UsageError("User not found.")
+ if _datastore.activate_user(user_obj):
+ click.secho(f'User "{user}" has been activated.', fg="green")
+ else:
+ click.secho(f'User "{user}" was already activated.', fg="yellow")
+
+
+@users.command("deactivate")
+@click.argument("user")
+@with_appcontext
+@commit
+def users_deactivate(user):
+ """Deactivate a user.
+
+ USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
+ """
+ user_obj = lookup_identity(user)
+ if user_obj is None:
+ raise click.UsageError("User not found.")
+ if _datastore.deactivate_user(user_obj):
+ click.secho(f'User "{user}" has been deactivated.', fg="green")
+ else:
+ click.secho(f'User "{user}" was already deactivated.', fg="yellow")
+
+
+@users.command("reset_access")
+@click.argument("user")
+@with_appcontext
+@commit
+def users_reset_access(user):
+ """Reset all authentication credentials for user.
+ This includes sessions, authentication tokens, two-factor
+ and unified sign in secrets. The user's password is not affected.
+
+ USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
+
+ """
+ user_obj = lookup_identity(user)
+ if user_obj is None:
+ raise click.UsageError("User not found.")
+ _datastore.reset_user_access(user_obj)
+ click.secho(
+ f'User "{user}" authentication credentials have been reset.', fg="green"
+ )
+
+
+@users.command("change_password")
+@click.argument("user")
+@click.password_option()
+@with_appcontext
+@commit
+def users_change_password(user, password):
+ """
+ Administratively change a user's password.
+ All the user's sessions will be immediately invalidated.
+ You will have to inform the user via an out of band mechanism
+ what their new password is.
+
+ USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
+
+ """
+ user_obj = lookup_identity(user)
+ if user_obj is None:
+ raise click.UsageError("User not found.")
+
+ kwargs = {"password": password, "password_confirm": password}
+ form = build_form("reset_password_form", meta={"csrf": False}, **kwargs)
+ form.user = user_obj
+
+ if form.validate():
+ # validation will normalize password
+ admin_change_password(user_obj, form.password.data, notify=False)
+ else:
+ raise click.UsageError(f"Error changing password. {fix_errors(form.errors)}")
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/confirmable.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/confirmable.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae5436ce1e3aaed101c3c834662b50bc3aade0ea
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/confirmable.py
@@ -0,0 +1,107 @@
+"""
+ flask_security.confirmable
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Flask-Security confirmable module
+
+ :copyright: (c) 2012 by Matt Wright.
+ :copyright: (c) 2017 by CERN.
+ :copyright: (c) 2021-2023 by J. Christopher Wagner (jwag).
+ :license: MIT, see LICENSE for more details.
+"""
+
+from flask import current_app
+
+from .proxies import _security, _datastore
+from .signals import confirm_instructions_sent, user_confirmed
+from .utils import (
+ config_value as cv,
+ get_token_status,
+ hash_data,
+ send_mail,
+ url_for_security,
+ verify_hash,
+)
+
+
+def generate_confirmation_link(user):
+ token = generate_confirmation_token(user)
+ return url_for_security("confirm_email", token=token, _external=True), token
+
+
+def send_confirmation_instructions(user):
+ """Sends the confirmation instructions email for the specified user.
+
+ :param user: The user to send the instructions to
+ """
+
+ confirmation_link, token = generate_confirmation_link(user)
+
+ send_mail(
+ cv("EMAIL_SUBJECT_CONFIRM"),
+ user.email,
+ "confirmation_instructions",
+ user=user,
+ confirmation_link=confirmation_link,
+ confirmation_token=token,
+ )
+
+ confirm_instructions_sent.send(
+ current_app._get_current_object(),
+ _async_wrapper=current_app.ensure_sync,
+ user=user,
+ token=token,
+ confirmation_token=token,
+ )
+
+
+def generate_confirmation_token(user):
+ """Generates a unique confirmation token for the specified user.
+
+ :param user: The user to work with
+ """
+ data = [str(user.fs_uniquifier), hash_data(user.email)]
+ return _security.confirm_serializer.dumps(data)
+
+
+def requires_confirmation(user):
+ """Returns `True` if the user requires confirmation."""
+ return (
+ _security.confirmable
+ and not cv("LOGIN_WITHOUT_CONFIRMATION")
+ and user.confirmed_at is None
+ )
+
+
+def confirm_email_token_status(token):
+ """Returns the expired status, invalid status, and user of a confirmation
+ token. For example::
+
+ expired, invalid, user = confirm_email_token_status('...')
+
+ :param token: The confirmation token
+ """
+ expired, invalid, user, token_data = get_token_status(
+ token, "confirm", "CONFIRM_EMAIL", return_data=True
+ )
+ if not invalid and user:
+ user_id, token_email_hash = token_data
+ invalid = not verify_hash(token_email_hash, user.email)
+ return expired, invalid, user
+
+
+def confirm_user(user):
+ """Confirms the specified user
+
+ :param user: The user to confirm
+ """
+ if user.confirmed_at is not None:
+ return False
+ user.confirmed_at = _security.datetime_factory()
+ _datastore.put(user)
+ user_confirmed.send(
+ current_app._get_current_object(),
+ _async_wrapper=current_app.ensure_sync,
+ user=user,
+ )
+ return True
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/core.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c07989e65972df516c0f9f6bb1bb892de79f596
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/core.py
@@ -0,0 +1,1964 @@
+"""
+ flask_security.core
+ ~~~~~~~~~~~~~~~~~~~
+
+ Flask-Security core module
+
+ :copyright: (c) 2012 by Matt Wright.
+ :copyright: (c) 2017 by CERN.
+ :copyright: (c) 2017 by ETH Zurich, Swiss Data Science Center.
+ :copyright: (c) 2019-2024 by J. Christopher Wagner (jwag).
+ :license: MIT, see LICENSE for more details.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from dataclasses import dataclass
+import importlib
+import typing as t
+import warnings
+
+from flask import current_app, g
+from flask_login import AnonymousUserMixin, LoginManager
+from flask_login import UserMixin as BaseUserMixin
+from flask_login import current_user
+from flask_principal import Identity, Principal, RoleNeed, UserNeed, identity_loaded
+from itsdangerous import URLSafeTimedSerializer
+from passlib.context import CryptContext
+from werkzeug.datastructures import ImmutableList
+from werkzeug.local import LocalProxy
+
+from .babel import FsDomain
+from .decorators import (
+ default_reauthn_handler,
+ default_unauthn_handler,
+ default_unauthz_handler,
+)
+from .forms import (
+ ChangePasswordForm,
+ ConfirmRegisterForm,
+ ForgotPasswordForm,
+ Form,
+ LoginForm,
+ PasswordlessLoginForm,
+ RegisterForm,
+ RegisterFormMixin,
+ ResetPasswordForm,
+ SendConfirmationForm,
+ TwoFactorVerifyCodeForm,
+ TwoFactorSetupForm,
+ TwoFactorRescueForm,
+ VerifyForm,
+ get_register_username_field,
+ login_username_field,
+)
+from .json import setup_json
+from .mail_util import MailUtil
+from .password_util import PasswordUtil
+from .phone_util import PhoneUtil
+from .oauth_glue import OAuthGlue
+from .proxies import _security
+from .recovery_codes import (
+ MfRecoveryForm,
+ MfRecoveryCodesForm,
+ MfRecoveryCodesUtil,
+)
+from .tf_plugin import TfPlugin, TwoFactorSelectForm
+from .twofactor import tf_send_security_token
+from .unified_signin import (
+ UnifiedSigninForm,
+ UnifiedSigninSetupForm,
+ UnifiedSigninSetupValidateForm,
+ UnifiedVerifyForm,
+ us_send_security_token,
+)
+from .webauthn import (
+ WebAuthnDeleteForm,
+ WebAuthnRegisterForm,
+ WebAuthnRegisterResponseForm,
+ WebAuthnSigninForm,
+ WebAuthnSigninResponseForm,
+ WebAuthnVerifyForm,
+)
+from .webauthn_util import WebauthnUtil
+from .username_util import UsernameUtil
+from .totp import Totp
+from .utils import _
+from .utils import config_value as cv
+from .utils import (
+ FsPermNeed,
+ csrf_cookie_handler,
+ default_render_template,
+ default_want_json,
+ get_identity_attribute,
+ get_identity_attributes,
+ get_message,
+ get_request_attr,
+ is_user_authenticated,
+ naive_utcnow,
+ parse_auth_token,
+ set_request_attr,
+ uia_email_mapper,
+ uia_username_mapper,
+ url_for_security,
+ verify_and_update_password,
+)
+from .views import create_blueprint, default_render_json
+
+if t.TYPE_CHECKING: # pragma: no cover
+ import flask
+ from flask import Request
+ from flask.typing import ResponseValue
+ import flask_login.mixins
+ from authlib.integrations.flask_client import OAuth
+ from .datastore import Role, User, UserDatastore
+
+
+# List of authentication mechanisms supported.
+AUTHN_MECHANISMS = ("basic", "session", "token")
+
+
+#: Default Flask-Security configuration
+_default_config: dict[str, t.Any] = {
+ "ANONYMOUS_USER_DISABLED": False,
+ "BLUEPRINT_NAME": "security",
+ "CLI_ROLES_NAME": "roles",
+ "CLI_USERS_NAME": "users",
+ "URL_PREFIX": None,
+ "STATIC_FOLDER": "static",
+ "STATIC_FOLDER_URL": "/fs-static",
+ "SUBDOMAIN": None,
+ "FLASH_MESSAGES": True,
+ "RETURN_GENERIC_RESPONSES": False,
+ "I18N_DOMAIN": "flask_security",
+ "I18N_DIRNAME": "builtin",
+ "EMAIL_VALIDATOR_ARGS": None,
+ "PASSWORD_HASH": "bcrypt",
+ "PASSWORD_SALT": None,
+ "PASSWORD_SINGLE_HASH": {
+ "django_argon2",
+ "django_bcrypt_sha256",
+ "django_pbkdf2_sha256",
+ "django_pbkdf2_sha1",
+ "django_bcrypt",
+ "django_salted_md5",
+ "django_salted_sha1",
+ "django_des_crypt",
+ "plaintext",
+ },
+ "PASSWORD_SCHEMES": [
+ "bcrypt",
+ "argon2",
+ "des_crypt",
+ "pbkdf2_sha256",
+ "pbkdf2_sha512",
+ "sha256_crypt",
+ "sha512_crypt",
+ # And always last one...
+ "plaintext",
+ ],
+ "PASSWORD_HASH_OPTIONS": {}, # Deprecated at passlib 1.7
+ "PASSWORD_HASH_PASSLIB_OPTIONS": {
+ "argon2__rounds": 10 # 1.7.1 default is 2.
+ }, # >= 1.7.1 method to pass options.
+ "PASSWORD_LENGTH_MIN": 8,
+ "PASSWORD_COMPLEXITY_CHECKER": None,
+ "PASSWORD_CHECK_BREACHED": False,
+ "PASSWORD_BREACHED_COUNT": 1,
+ "PASSWORD_NORMALIZE_FORM": "NFKD",
+ "PASSWORD_REQUIRED": True,
+ "DEPRECATED_PASSWORD_SCHEMES": ["auto"],
+ "LOGIN_URL": "/login",
+ "LOGOUT_URL": "/logout",
+ "REGISTER_URL": "/register",
+ "RESET_URL": "/reset",
+ "CHANGE_URL": "/change",
+ "CONFIRM_URL": "/confirm",
+ "VERIFY_URL": "/verify",
+ "TWO_FACTOR_SETUP_URL": "/tf-setup",
+ "TWO_FACTOR_TOKEN_VALIDATION_URL": "/tf-validate",
+ "TWO_FACTOR_RESCUE_URL": "/tf-rescue",
+ "TWO_FACTOR_SELECT_URL": "/tf-select",
+ "TWO_FACTOR_POST_SETUP_VIEW": ".two_factor_setup", # endpoint or URL
+ "TWO_FACTOR_ERROR_VIEW": ".login",
+ "LOGOUT_METHODS": ["GET", "POST"],
+ "POST_LOGIN_VIEW": "/",
+ "POST_LOGOUT_VIEW": "/",
+ "LOGIN_ERROR_VIEW": None, # spa
+ "POST_OAUTH_LOGIN_VIEW": None, # spa
+ "CONFIRM_ERROR_VIEW": None, # spa
+ "POST_CONFIRM_VIEW": None, # spa
+ "RESET_VIEW": None, # spa
+ "RESET_ERROR_VIEW": None, # spa
+ "POST_RESET_VIEW": None,
+ "POST_CHANGE_VIEW": None,
+ "POST_VERIFY_VIEW": None,
+ "POST_REGISTER_VIEW": None,
+ "UNAUTHORIZED_VIEW": None,
+ "REQUIRES_CONFIRMATION_ERROR_VIEW": None,
+ "REDIRECT_HOST": None,
+ "REDIRECT_BEHAVIOR": None,
+ "REDIRECT_ALLOW_SUBDOMAINS": False,
+ "FORGOT_PASSWORD_TEMPLATE": "security/forgot_password.html",
+ "LOGIN_USER_TEMPLATE": "security/login_user.html",
+ "REGISTER_USER_TEMPLATE": "security/register_user.html",
+ "RESET_PASSWORD_TEMPLATE": "security/reset_password.html",
+ "CHANGE_PASSWORD_TEMPLATE": "security/change_password.html",
+ "SEND_CONFIRMATION_TEMPLATE": "security/send_confirmation.html",
+ "SEND_LOGIN_TEMPLATE": "security/send_login.html",
+ "VERIFY_TEMPLATE": "security/verify.html",
+ "TWO_FACTOR_VERIFY_CODE_TEMPLATE": "security/two_factor_verify_code.html",
+ "TWO_FACTOR_SETUP_TEMPLATE": "security/two_factor_setup.html",
+ "TWO_FACTOR_SELECT_TEMPLATE": "security/two_factor_select.html",
+ "CONFIRMABLE": False,
+ "REGISTERABLE": False,
+ "RECOVERABLE": False,
+ "TRACKABLE": False,
+ "PASSWORDLESS": False,
+ "CHANGEABLE": False,
+ "TWO_FACTOR": False,
+ "SEND_REGISTER_EMAIL": True,
+ "SEND_PASSWORD_CHANGE_EMAIL": True,
+ "SEND_PASSWORD_RESET_EMAIL": True,
+ "SEND_PASSWORD_RESET_NOTICE_EMAIL": True,
+ "LOGIN_WITHIN": "1 days",
+ "TWO_FACTOR_AUTHENTICATOR_VALIDITY": 120,
+ "TWO_FACTOR_MAIL_VALIDITY": 300,
+ "TWO_FACTOR_SMS_VALIDITY": 120,
+ "TWO_FACTOR_ALWAYS_VALIDATE": True,
+ "TWO_FACTOR_LOGIN_VALIDITY": "30 days",
+ "TWO_FACTOR_VALIDITY_SALT": "tf-validity-salt",
+ "TWO_FACTOR_VALIDITY_COOKIE": {
+ "httponly": True,
+ "secure": False,
+ "samesite": "Strict",
+ },
+ "TWO_FACTOR_RESCUE_EMAIL": True,
+ "MULTI_FACTOR_RECOVERY_CODES": False,
+ "MULTI_FACTOR_RECOVERY_CODES_N": 5,
+ "MULTI_FACTOR_RECOVERY_CODES_URL": "/mf-recovery-codes",
+ "MULTI_FACTOR_RECOVERY_CODES_TEMPLATE": "security/mf_recovery_codes.html",
+ "MULTI_FACTOR_RECOVERY_URL": "/mf-recovery",
+ "MULTI_FACTOR_RECOVERY_TEMPLATE": "security/mf_recovery.html",
+ "MULTI_FACTOR_RECOVERY_CODES_KEYS": None,
+ "MULTI_FACTOR_RECOVERY_CODE_TTL": None,
+ "OAUTH_ENABLE": False,
+ "OAUTH_BUILTIN_PROVIDERS": ["github", "google"],
+ "OAUTH_START_URL": "/login/oauthstart",
+ "OAUTH_RESPONSE_URL": "/login/oauthresponse",
+ "CONFIRM_EMAIL_WITHIN": "5 days",
+ "RESET_PASSWORD_WITHIN": "1 days",
+ "LOGIN_WITHOUT_CONFIRMATION": False,
+ "AUTO_LOGIN_AFTER_CONFIRM": False,
+ "AUTO_LOGIN_AFTER_RESET": False,
+ "EMAIL_SENDER": LocalProxy(
+ lambda: current_app.config.get("MAIL_DEFAULT_SENDER", "no-reply@localhost")
+ ),
+ "TWO_FACTOR_RESCUE_MAIL": "no-reply@localhost",
+ "TOKEN_AUTHENTICATION_KEY": "auth_token",
+ "TOKEN_AUTHENTICATION_HEADER": "Authentication-Token",
+ "TOKEN_MAX_AGE": None,
+ "TOKEN_EXPIRE_TIMESTAMP": lambda user: 0,
+ "CONFIRM_SALT": "confirm-salt",
+ "RESET_SALT": "reset-salt",
+ "LOGIN_SALT": "login-salt",
+ "CHANGE_SALT": "change-salt",
+ "REMEMBER_SALT": "remember-salt",
+ "DEFAULT_REMEMBER_ME": False,
+ "DEFAULT_HTTP_AUTH_REALM": _("Login Required"),
+ "EMAIL_SUBJECT_REGISTER": _("Welcome"),
+ "EMAIL_SUBJECT_CONFIRM": _("Please confirm your email"),
+ "EMAIL_SUBJECT_PASSWORDLESS": _("Login instructions"),
+ "EMAIL_SUBJECT_PASSWORD_NOTICE": _("Your password has been reset"),
+ "EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE": _("Your password has been changed"),
+ "EMAIL_SUBJECT_PASSWORD_RESET": _("Password reset instructions"),
+ "EMAIL_PLAINTEXT": True,
+ "EMAIL_HTML": True,
+ "EMAIL_SUBJECT_TWO_FACTOR": _("Two-factor Login"),
+ "EMAIL_SUBJECT_TWO_FACTOR_RESCUE": _("Two-factor Rescue"),
+ "USER_IDENTITY_ATTRIBUTES": [
+ {"email": {"mapper": uia_email_mapper, "case_insensitive": True}}
+ ],
+ "PHONE_REGION_DEFAULT": "US",
+ "FRESHNESS": timedelta(hours=24),
+ "FRESHNESS_GRACE_PERIOD": timedelta(hours=1),
+ "API_ENABLED_METHODS": ["session", "token"],
+ "HASHING_SCHEMES": ["sha256_crypt", "hex_md5"],
+ "DEPRECATED_HASHING_SCHEMES": ["hex_md5"],
+ "DATETIME_FACTORY": naive_utcnow,
+ "TOTP_SECRETS": None,
+ "TOTP_ISSUER": None,
+ "SMS_SERVICE": "Dummy",
+ "SMS_SERVICE_CONFIG": {
+ "ACCOUNT_SID": None,
+ "AUTH_TOKEN": None,
+ "PHONE_NUMBER": None,
+ },
+ "TWO_FACTOR_REQUIRED": False,
+ "TWO_FACTOR_SECRET": None, # Deprecated - use TOTP_SECRETS
+ "TWO_FACTOR_ENABLED_METHODS": ["email", "authenticator", "sms"],
+ "TWO_FACTOR_URI_SERVICE_NAME": "service_name", # Deprecated - use TOTP_ISSUER
+ "TWO_FACTOR_SMS_SERVICE": "Dummy", # Deprecated - use SMS_SERVICE
+ "TWO_FACTOR_SMS_SERVICE_CONFIG": { # Deprecated - use SMS_SERVICE_CONFIG
+ "ACCOUNT_SID": None,
+ "AUTH_TOKEN": None,
+ "PHONE_NUMBER": None,
+ },
+ "TWO_FACTOR_IMPLEMENTATIONS": {
+ "code": "flask_security.twofactor.CodeTfPlugin",
+ "webauthn": "flask_security.webauthn.WebAuthnTfPlugin",
+ },
+ "UNIFIED_SIGNIN": False,
+ "US_SETUP_SALT": "us-setup-salt",
+ "US_SIGNIN_URL": "/us-signin",
+ "US_SIGNIN_SEND_CODE_URL": "/us-signin/send-code",
+ "US_SETUP_URL": "/us-setup",
+ "US_VERIFY_URL": "/us-verify",
+ "US_VERIFY_SEND_CODE_URL": "/us-verify/send-code",
+ "US_VERIFY_LINK_URL": "/us-verify-link",
+ "US_POST_SETUP_VIEW": ".us_setup", # endpoint or URL
+ "US_SIGNIN_TEMPLATE": "security/us_signin.html",
+ "US_SETUP_TEMPLATE": "security/us_setup.html",
+ "US_VERIFY_TEMPLATE": "security/us_verify.html",
+ "US_ENABLED_METHODS": ["password", "email", "authenticator", "sms"],
+ "US_MFA_REQUIRED": ["password", "email"],
+ "US_TOKEN_VALIDITY": 120,
+ "US_EMAIL_SUBJECT": _("Verification Code"),
+ "US_SETUP_WITHIN": "30 minutes",
+ "US_SIGNIN_REPLACES_LOGIN": False,
+ "CSRF_PROTECT_MECHANISMS": AUTHN_MECHANISMS,
+ "CSRF_IGNORE_UNAUTH_ENDPOINTS": False,
+ "CSRF_COOKIE_NAME": None,
+ "CSRF_COOKIE": {
+ "samesite": "Strict",
+ "httponly": False,
+ "secure": False,
+ },
+ "CSRF_HEADER": "X-XSRF-Token",
+ "CSRF_COOKIE_REFRESH_EACH_REQUEST": False,
+ "BACKWARDS_COMPAT_UNAUTHN": False,
+ "BACKWARDS_COMPAT_AUTH_TOKEN": False,
+ "JOIN_USER_ROLES": True,
+ "USERNAME_ENABLE": False,
+ "USERNAME_REQUIRED": False,
+ "USERNAME_MIN_LENGTH": 4,
+ "USERNAME_MAX_LENGTH": 32,
+ "USERNAME_NORMALIZE_FORM": "NFKD",
+ "WEBAUTHN": False,
+ "WAN_CHALLENGE_BYTES": None, # uses system default
+ "WAN_POST_REGISTER_VIEW": ".wan_register", # endpoint or URL
+ "WAN_RP_NAME": "My Flask App",
+ "WAN_SALT": "wan-salt",
+ "WAN_REGISTER_TIMEOUT": 60000, # milliseconds
+ "WAN_REGISTER_TEMPLATE": "security/wan_register.html",
+ "WAN_REGISTER_URL": "/wan-register",
+ "WAN_REGISTER_WITHIN": "30 minutes",
+ "WAN_SIGNIN_TIMEOUT": 60000, # milliseconds
+ "WAN_SIGNIN_TEMPLATE": "security/wan_signin.html",
+ "WAN_SIGNIN_URL": "/wan-signin",
+ "WAN_SIGNIN_WITHIN": "1 minutes",
+ "WAN_DELETE_URL": "/wan-delete",
+ "WAN_VERIFY_URL": "/wan-verify",
+ "WAN_VERIFY_TEMPLATE": "security/wan_verify.html",
+ "WAN_ALLOW_AS_FIRST_FACTOR": True,
+ "WAN_ALLOW_AS_MULTI_FACTOR": True,
+ "WAN_ALLOW_USER_HINTS": True,
+ "WAN_ALLOW_AS_VERIFY": ["first", "secondary"],
+ "ZXCVBN_MINIMUM_SCORE": 3,
+}
+
+#: Default Flask-Security messages
+_default_messages = {
+ "API_ERROR": (_("Input not appropriate for requested API"), "error"),
+ "GENERIC_AUTHN_FAILED": (
+ _("Authentication failed - identity or password/passcode invalid"),
+ "error",
+ ),
+ "GENERIC_RECOVERY": (
+ _(
+ "If that email address is in our system, "
+ "you will receive an email describing how to reset your password."
+ ),
+ "info",
+ ),
+ "GENERIC_US_SIGNIN": (
+ _("If that identity is in our system, you were sent a code."),
+ "info",
+ ),
+ "UNAUTHORIZED": (_("You do not have permission to view this resource."), "error"),
+ "UNAUTHENTICATED": (
+ _("You must sign in to view this resource."),
+ "error",
+ ),
+ "REAUTHENTICATION_REQUIRED": (
+ _("You must re-authenticate to access this endpoint"),
+ "error",
+ ),
+ "CONFIRM_REGISTRATION": (
+ _(
+ "Thank you. To confirm your email address %(email)s,"
+ " please click on the link"
+ " in the email we have just sent to you."
+ ),
+ "success",
+ ),
+ "EMAIL_CONFIRMED": (_("Thank you. Your email has been confirmed."), "success"),
+ "ALREADY_CONFIRMED": (_("Your email has already been confirmed."), "info"),
+ "INVALID_CONFIRMATION_TOKEN": (_("Invalid confirmation token."), "error"),
+ "EMAIL_ALREADY_ASSOCIATED": (
+ _("%(email)s is already associated with an account."),
+ "error",
+ ),
+ "IDENTITY_ALREADY_ASSOCIATED": (
+ _(
+ "Identity attribute '%(attr)s' with value '%(value)s' is already"
+ " associated with an account."
+ ),
+ "error",
+ ),
+ "IDENTITY_NOT_REGISTERED": (
+ _("Identity %(id)s not registered"),
+ "error",
+ ),
+ "OAUTH_HANDSHAKE_ERROR": (
+ _(
+ "An error occurred while communicating with the Oauth provider:"
+ " (%(exerror)s - %(exdesc)s). "
+ "Please try again."
+ ),
+ "error",
+ ),
+ "PASSWORD_MISMATCH": (_("Password does not match"), "error"),
+ "RETYPE_PASSWORD_MISMATCH": (_("Passwords do not match"), "error"),
+ "INVALID_REDIRECT": (_("Redirections outside the domain are forbidden"), "error"),
+ "INVALID_RECOVERY_CODE": (_("Recovery code invalid"), "error"),
+ "NO_RECOVERY_CODES_SETUP": (_("No recovery codes generated yet"), "info"),
+ "PASSWORD_RESET_REQUEST": (
+ _("Instructions to reset your password have been sent to %(email)s."),
+ "info",
+ ),
+ "PASSWORD_RESET_EXPIRED": (
+ _("You did not reset your password within %(within)s. "),
+ "error",
+ ),
+ "INVALID_RESET_PASSWORD_TOKEN": (_("Invalid reset password token."), "error"),
+ "CONFIRMATION_REQUIRED": (_("Email requires confirmation."), "error"),
+ "CONFIRMATION_REQUEST": (
+ _("Confirmation instructions have been sent to %(email)s."),
+ "info",
+ ),
+ "CONFIRMATION_EXPIRED": (
+ _("You did not confirm your email within %(within)s. "),
+ "error",
+ ),
+ "LOGIN_EXPIRED": (
+ _(
+ "You did not login within %(within)s. New instructions to login "
+ "have been sent to %(email)s."
+ ),
+ "error",
+ ),
+ "LOGIN_EMAIL_SENT": (
+ _("Instructions to login have been sent to %(email)s."),
+ "success",
+ ),
+ "INVALID_LOGIN_TOKEN": (_("Invalid login token."), "error"),
+ "DISABLED_ACCOUNT": (_("Account is disabled."), "error"),
+ "EMAIL_NOT_PROVIDED": (_("Email not provided"), "error"),
+ "INVALID_EMAIL_ADDRESS": (_("Invalid email address"), "error"),
+ "INVALID_CODE": (_("Invalid code"), "error"),
+ "PASSWORD_NOT_PROVIDED": (_("Password not provided"), "error"),
+ "PASSWORD_INVALID_LENGTH": (
+ _("Password must be at least %(length)s characters"),
+ "error",
+ ),
+ "PASSWORD_TOO_SIMPLE": (_("Password not complex enough"), "error"),
+ "PASSWORD_BREACHED": (_("Password on breached list"), "error"),
+ "PASSWORD_BREACHED_SITE_ERROR": (
+ _("Failed to contact breached passwords site"),
+ "error",
+ ),
+ "PHONE_INVALID": (_("Phone number not valid e.g. missing country code"), "error"),
+ "USER_DOES_NOT_EXIST": (_("Specified user does not exist"), "error"),
+ "INVALID_PASSWORD": (_("Invalid password"), "error"),
+ "INVALID_PASSWORD_CODE": (_("Password or code submitted is not valid"), "error"),
+ "PASSWORDLESS_LOGIN_SUCCESSFUL": (_("You have successfully logged in."), "success"),
+ "FORGOT_PASSWORD": (_("Forgot password?"), "info"),
+ "PASSWORD_RESET": (
+ _(
+ "You successfully reset your password and you have been logged in "
+ "automatically."
+ ),
+ "success",
+ ),
+ "PASSWORD_RESET_NO_LOGIN": (
+ _(
+ "You successfully reset your password."
+ " Please authenticate using your new password."
+ ),
+ "success",
+ ),
+ "PASSWORD_IS_THE_SAME": (
+ _("Your new password must be different than your previous password."),
+ "error",
+ ),
+ "PASSWORD_CHANGE": (_("You successfully changed your password."), "success"),
+ "LOGIN": (_("Please log in to access this page."), "info"),
+ "REFRESH": (_("Please reauthenticate to access this page."), "info"),
+ "REAUTHENTICATION_SUCCESSFUL": (_("Reauthentication successful"), "info"),
+ "ANONYMOUS_USER_REQUIRED": (
+ _("You can only access this endpoint when not logged in."),
+ "error",
+ ),
+ "CODE_HAS_BEEN_SENT": (_("Code has been sent."), "info"),
+ "FAILED_TO_SEND_CODE": (_("Failed to send code. Please try again later"), "error"),
+ "TWO_FACTOR_INVALID_TOKEN": (_("Invalid code"), "error"),
+ "TWO_FACTOR_LOGIN_SUCCESSFUL": (_("Your code has been confirmed"), "success"),
+ "TWO_FACTOR_CHANGE_METHOD_SUCCESSFUL": (
+ _("You successfully changed your two-factor method."),
+ "success",
+ ),
+ "TWO_FACTOR_PERMISSION_DENIED": (
+ _("You currently do not have permissions to access this page"),
+ "error",
+ ),
+ "TWO_FACTOR_METHOD_NOT_AVAILABLE": (_("Marked method is not valid"), "error"),
+ "TWO_FACTOR_DISABLED": (
+ _("You successfully disabled two factor authorization."),
+ "success",
+ ),
+ "US_CURRENT_METHODS": (
+ _("Currently active sign in options: %(method_list)s."),
+ "info",
+ ),
+ "US_METHOD_NOT_AVAILABLE": (_("Requested method is not valid"), "error"),
+ "US_SETUP_EXPIRED": (
+ _("Setup must be completed within %(within)s. Please start over."),
+ "error",
+ ),
+ "US_SETUP_SUCCESSFUL": (_("Unified sign in setup successful"), "info"),
+ "US_SPECIFY_IDENTITY": (_("You must specify a valid identity to sign in"), "error"),
+ "USE_CODE": (_("Use this code to sign in: %(code)s."), "info"),
+ "USERNAME_INVALID_LENGTH": (
+ _(
+ "Username must be at least %(min)d characters and less than"
+ " %(max)d characters"
+ ),
+ "error",
+ ),
+ "USERNAME_ILLEGAL_CHARACTERS": (
+ _("Username contains illegal characters"),
+ "error",
+ ),
+ "USERNAME_DISALLOWED_CHARACTERS": (
+ _("Username can contain only letters and numbers"),
+ "error",
+ ),
+ "USERNAME_NOT_PROVIDED": (_("Username not provided"), "error"),
+ "USERNAME_ALREADY_ASSOCIATED": (
+ _("%(username)s is already associated with an account."),
+ "error",
+ ),
+ "WEBAUTHN_EXPIRED": (
+ _("WebAuthn operation must be completed within %(within)s. Please start over."),
+ "error",
+ ),
+ "WEBAUTHN_NAME_REQUIRED": (
+ _("Nickname for new credential is required."),
+ "error",
+ ),
+ "WEBAUTHN_NAME_INUSE": (
+ _("%(name)s is already associated with a credential."),
+ "error",
+ ),
+ "WEBAUTHN_NAME_NOT_FOUND": (
+ _("%(name)s not registered with current user."),
+ "error",
+ ),
+ "WEBAUTHN_CREDENTIAL_DELETED": (
+ _("Successfully deleted WebAuthn credential with name: %(name)s"),
+ "info",
+ ),
+ "WEBAUTHN_REGISTER_SUCCESSFUL": (
+ _("Successfully added WebAuthn credential with name: %(name)s"),
+ "info",
+ ),
+ "WEBAUTHN_CREDENTIAL_ID_INUSE": (
+ _("WebAuthn credential id already registered."),
+ "error",
+ ),
+ "WEBAUTHN_UNKNOWN_CREDENTIAL_ID": (
+ _("Unregistered WebAuthn credential id."),
+ "error",
+ ),
+ "WEBAUTHN_ORPHAN_CREDENTIAL_ID": (
+ _("WebAuthn credential doesn't belong to any user."),
+ "error",
+ ),
+ "WEBAUTHN_NO_VERIFY": (
+ _("Could not verify WebAuthn credential: %(cause)s."),
+ "error",
+ ),
+ "WEBAUTHN_CREDENTIAL_WRONG_USAGE": (
+ _("Credential not registered for this use (first or secondary)"),
+ "error",
+ ),
+ "WEBAUTHN_MISMATCH_USER_HANDLE": (
+ _("Credential user handle didn't match"),
+ "error",
+ ),
+}
+
+
+def _default_form_instantiator(
+ name: str, cls: t.Type[Form], *args: t.Any, **kwargs: dict[str, t.Any]
+) -> Form:
+ return cls(*args, **kwargs)
+
+
+@dataclass
+class FormInfo:
+ """
+ Each view form has a name - assigned by Flask-Security.
+ As part of every request, the form is instantiated using (usually) request.form or
+ request.json.
+ The default instantiator simply uses the class constructor - however
+ applications can provide their OWN instantiator which can do pretty much anything
+ as long as it returns an instantiated form. The 'cls' argument is optional since
+ the instantiator COULD be form specific.
+
+ The instantiator callable will always be called from a flask request context
+ and receive the following arguments::
+
+ (name, form_cls_name (optional), **kwargs)
+
+ kwargs will always have `formdata` and often will have `meta`. All kwargs
+ must be passed to the underlying form constructor.
+
+ See :py:meth:`flask_security.Security.set_form_info`
+
+ .. versionadded:: 5.1.0
+ """
+
+ instantiator: t.Callable[..., Form] = _default_form_instantiator
+ cls: t.Type[Form] | None = None
+
+
+def _user_loader(user_id):
+ """Load based on fs_uniquifier (alternative_id)."""
+ user = _security.datastore.find_user(fs_uniquifier=str(user_id))
+ if user and user.active:
+ set_request_attr("fs_authn_via", "session")
+ return user
+ return None
+
+
+def _request_loader(request):
+ # Short-circuit if we have already been called and verified.
+ # This can happen since Flask-Login will call us (if no session) and our own
+ # decorator @auth_token_required can call us.
+ # N.B. we don't call current_user here since that in fact might try and LOAD
+ # a user - which would call us again.
+ if get_request_attr("fs_authn_via") == "token":
+ return g._login_user
+
+ header_key = cv("TOKEN_AUTHENTICATION_HEADER")
+ args_key = cv("TOKEN_AUTHENTICATION_KEY")
+ header_token = request.headers.get(header_key, None)
+ token = request.args.get(args_key, header_token)
+ if request.is_json:
+ data = request.get_json(silent=True) or {}
+ if isinstance(data, dict):
+ token = data.get(args_key, token)
+
+ try:
+ tdata = parse_auth_token(token)
+ if hasattr(_security.datastore.user_model, "fs_token_uniquifier"):
+ user = _security.datastore.find_user(fs_token_uniquifier=tdata["uid"])
+ else:
+ user = _security.datastore.find_user(fs_uniquifier=tdata["uid"])
+ except Exception:
+ return None
+
+ if user and user.active and user.verify_auth_token(tdata):
+ set_request_attr("fs_authn_via", "token")
+ return user
+
+ return None
+
+
+def _identity_loader():
+ # N.B. once AnonymousUser is gone - can just check current_user
+ if current_user and hasattr(current_user, "fs_uniquifier"):
+ return Identity(current_user.fs_uniquifier)
+ return None
+
+
+def _on_identity_loaded(sender, identity):
+ if current_user and hasattr(current_user, "fs_uniquifier"):
+ identity.provides.add(UserNeed(current_user.fs_uniquifier))
+
+ for role in getattr(current_user, "roles", []):
+ identity.provides.add(RoleNeed(role.name))
+ for fsperm in role.get_permissions():
+ identity.provides.add(FsPermNeed(fsperm))
+
+ identity.user = current_user
+
+
+def _get_login_manager(app, security):
+ lm = LoginManager()
+ # Flask-Login is likely going in the direction of removing AnonymousUser
+ # however this might wreak havoc on applications that just assume that
+ # current_user is always set.
+ if cv("ANONYMOUS_USER_DISABLED", app=app):
+ lm.anonymous_user = lambda: None
+ else:
+ lm.anonymous_user = AnonymousUser
+
+ lm.user_loader(_user_loader)
+ lm.request_loader(_request_loader)
+ # Set Flask-Login handler so @login_required will have same behavior as
+ # @auth_required
+ lm.unauthorized_callback = security._unauthn_handler
+
+ # Note: since we redirect unauthenticated requests to us - we no longer need to
+ # mess with Flask-Login login_view, or message settings.
+ # We also (5.4.0) stop doing anything with need_fresh_login - we support time-based
+ # freshness.
+
+ lm.init_app(app)
+ return lm
+
+
+def _get_principal(app):
+ p = Principal(app, use_sessions=False)
+ p.identity_loader(_identity_loader)
+ return p
+
+
+def _get_pwd_context(app: flask.Flask) -> CryptContext:
+ pw_hash = cv("PASSWORD_HASH", app=app)
+ schemes = cv("PASSWORD_SCHEMES", app=app)
+ deprecated = cv("DEPRECATED_PASSWORD_SCHEMES", app=app)
+ if pw_hash not in schemes:
+ allowed = ", ".join(schemes[:-1]) + " and " + schemes[-1]
+ raise ValueError(
+ f"Invalid password hashing scheme {pw_hash}. Allowed values are {allowed}"
+ )
+ cc = CryptContext(
+ schemes=schemes,
+ default=pw_hash,
+ deprecated=deprecated,
+ **cv("PASSWORD_HASH_PASSLIB_OPTIONS", app=app),
+ )
+ return cc
+
+
+def _get_hashing_context(app: flask.Flask) -> CryptContext:
+ schemes = cv("HASHING_SCHEMES", app=app)
+ deprecated = cv("DEPRECATED_HASHING_SCHEMES", app=app)
+ return CryptContext(schemes=schemes, deprecated=deprecated)
+
+
+def _get_serializer(app, name):
+ secret_key = app.config.get("SECRET_KEY")
+ salt = cv(f"{name.upper()}_SALT", app=app)
+ return URLSafeTimedSerializer(secret_key=secret_key, salt=salt)
+
+
+def _context_processor():
+ return dict(
+ url_for_security=url_for_security,
+ security=_security,
+ _fs_is_user_authenticated=is_user_authenticated,
+ )
+
+
+class RoleMixin:
+ """Mixin for `Role` model definitions"""
+
+ if t.TYPE_CHECKING: # pragma: no cover
+
+ def __init__(self) -> None:
+ self.permissions: list[str] | None
+
+ def __eq__(self, other):
+ return self.name == other or self.name == getattr(other, "name", None)
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __hash__(self):
+ return hash(self.name)
+
+ def get_permissions(self) -> set:
+ """
+ Return set of permissions associated with role.
+
+ .. versionadded:: 3.3.0
+ """
+ if hasattr(self, "permissions") and self.permissions:
+ return set(self.permissions)
+ return set()
+
+
+class UserMixin(BaseUserMixin):
+ """Mixin for `User` model definitions"""
+
+ def get_id(self) -> str:
+ """Returns the user identification attribute. 'Alternative-token' for
+ Flask-Login. This is always ``fs_uniquifier``.
+
+ .. versionadded:: 3.4.0
+ """
+ return str(self.fs_uniquifier)
+
+ @property
+ def is_active(self) -> bool:
+ """Returns `True` if the user is active."""
+ return self.active
+
+ def get_auth_token(self) -> str | bytes:
+ """Constructs the user's authentication token.
+
+ :raises ValueError: If ``fs_token_uniquifier`` is part of model but not set.
+
+ Optionally use a separate uniquifier so that changing password doesn't
+ invalidate auth tokens.
+
+ The returned value is securely signed using the ``remember_token_serializer``
+
+ .. versionchanged:: 4.0.0
+ If user model has ``fs_token_uniquifier`` - use that (raise ValueError
+ if not set). Otherwise, fallback to using ``fs_uniquifier``.
+ .. versionchanged:: 5.4.0
+ New format - a dict with a version string. Add a token-based expiry
+ option as well as a session id.
+ """
+
+ tdata: dict[str, t.Any] = dict(ver=str(5))
+ if hasattr(self, "fs_token_uniquifier"):
+ if not self.fs_token_uniquifier:
+ raise ValueError()
+ tdata["uid"] = str(self.fs_token_uniquifier)
+ else:
+ tdata["uid"] = str(self.fs_uniquifier)
+ tdata["sid"] = 0 # session id
+ tdata["exp"] = int(cv("TOKEN_EXPIRE_TIMESTAMP")(self)) # if >0 then shorter of
+ # :data:SECURITY_MAX_AGE and this.
+
+ # Let application add things
+ self.augment_auth_token(tdata)
+
+ # Serialize and sign
+ return _security.remember_token_serializer.dumps(tdata)
+
+ def augment_auth_token(self, tdata: dict[str, t.Any]) -> None:
+ """Override this to add/modify parts of the auth token.
+ Additions to the dict can be made and verified in verify_auth_token()
+
+ .. versionadded:: 5.4.0
+ """
+ return
+
+ def verify_auth_token(self, tdata: dict[str, t.Any]) -> bool:
+ """
+ Override this to perform additional verification of contents of auth token.
+ Prior to this being called the token has been validated (via signing)
+ and has not expired (either with MAX_AGE or specific 'exp' value).
+
+ :param tdata: a dictionary just as in augment_auth_token()
+ :return: True if auth token represented by tdata is valid, False otherwise.
+
+ .. versionadded:: 3.3.0
+
+ .. versionchanged:: 5.4.0
+ Now receives a dictionary.
+ """
+ return True
+
+ def has_role(self, role: str | Role) -> bool:
+ """Returns `True` if the user identifies with the specified role.
+
+ :param role: A role name or `Role` instance"""
+ if isinstance(role, str):
+ return role in (role.name for role in self.roles)
+ else:
+ return role in self.roles
+
+ def has_permission(self, permission: str) -> bool:
+ """
+ Returns `True` if user has this permission (via a role it has).
+
+ :param permission: permission string name
+
+ .. versionadded:: 3.3.0
+
+ """
+ for role in self.roles:
+ if permission in role.get_permissions():
+ return True
+ return False
+
+ def get_security_payload(self) -> dict[str, t.Any]:
+ """Serialize user object as response payload.
+ Override this to return any/all of the user object in JSON responses.
+ Return a dict.
+ """
+ return {}
+
+ def get_redirect_qparams(
+ self, existing: dict[str, t.Any] | None = None
+ ) -> dict[str, t.Any]:
+ """Return user info that will be added to redirect query params.
+
+ :param existing: A dict that will be updated.
+ :return: A dict whose keys will be query params and values will be query values.
+
+ The returned dict will always have an 'identity' key/value.
+ If the User Model contains 'email', an 'email' key/value will be added.
+ All keys provided in 'existing' will also be merged in.
+
+ .. versionadded:: 3.2.0
+
+ .. versionchanged:: 4.0.0
+ Add 'identity' using UserMixin.calc_username() - email is optional.
+ """
+ if not existing:
+ existing = {}
+ if hasattr(self, "email"):
+ existing.update({"email": self.email})
+ existing.update({"identity": self.calc_username()})
+ return existing
+
+ def verify_and_update_password(self, password: str) -> bool:
+ """Returns ``True`` if the password is valid for the specified user.
+
+ Additionally, the hashed password in the database is updated if the
+ hashing algorithm happens to have changed.
+
+ N.B. you MUST call DB commit if you are using a session-based datastore
+ (such as SqlAlchemy) since the user instance might have been altered
+ (i.e. ``app.security.datastore.commit()``).
+ This is usually handled in the view.
+
+ :param password: A plaintext password to verify
+
+ .. versionadded:: 3.2.0
+ """
+ return verify_and_update_password(password, self)
+
+ def calc_username(self) -> str:
+ """Come up with the best 'username' based on how the app
+ is configured (via :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`).
+ Returns the first non-null match (and converts to string).
+ In theory this should NEVER be the empty string unless the user
+ record isn't actually valid.
+
+ .. versionadded:: 3.4.0
+ """
+ cusername = None
+ for attr in get_identity_attributes():
+ cusername = getattr(self, attr, None)
+ if cusername is not None and len(str(cusername)) > 0:
+ break
+ return str(cusername) if cusername is not None else ""
+
+ def us_send_security_token(self, method: str, **kwargs: t.Any) -> str | None:
+ """Generate and send the security code for unified sign in.
+
+ :param method: The method in which the code will be sent
+ :param kwargs: Opaque parameters that are subject to change at any time
+ :return: None if successful, error message if not.
+
+ This is a wrapper around :meth:`us_send_security_token`
+ that can be overridden to manage any errors.
+
+ .. versionadded:: 3.4.0
+ """
+ try:
+ us_send_security_token(self, method, **kwargs)
+ except Exception:
+ return get_message("FAILED_TO_SEND_CODE")[0]
+ return None
+
+ def tf_send_security_token(self, method: str, **kwargs: t.Any) -> str | None:
+ """Generate and send the security code for two-factor.
+
+ :param method: The method in which the code will be sent
+ :param kwargs: Opaque parameters that are subject to change at any time
+ :return: None if successful, error message if not.
+
+ This is a wrapper around :meth:`tf_send_security_token`
+ that can be overridden to manage any errors.
+
+ .. versionadded:: 3.4.0
+ """
+ try:
+ tf_send_security_token(self, method, **kwargs)
+ except Exception:
+ return get_message("FAILED_TO_SEND_CODE")[0]
+ return None
+
+
+class WebAuthnMixin:
+ def get_user_mapping(self) -> dict[str, t.Any]:
+ """
+ Return the filter needed by find_user() to get the user
+ associated with this webauthn credential.
+ Note that this probably has to be overridden using mongoengine.
+
+ .. versionadded:: 5.0.0
+ """
+ return dict(id=self.user_id) # type: ignore
+
+
+class AnonymousUser(AnonymousUserMixin):
+ """AnonymousUser definition"""
+
+ def __init__(self):
+ self.roles = ImmutableList()
+
+ def has_role(self, *args):
+ """Returns `False`"""
+ return False
+
+
+class Security:
+ """The :class:`Security` class initializes the Flask-Security extension.
+
+ :param app: The application.
+ :param datastore: An instance of a user datastore.
+ :param register_blueprint: to register the Security blueprint or not.
+ :param login_form: set form for the login view
+ :param verify_form: set form for re-authentication due to freshness check
+ :param register_form: set form for the register view when
+ *SECURITY_CONFIRMABLE* is false
+ :param confirm_register_form: set form for the register view when
+ *SECURITY_CONFIRMABLE* is true
+ :param forgot_password_form: set form for the forgot password view
+ :param reset_password_form: set form for the reset password view
+ :param change_password_form: set form for the change password view
+ :param send_confirmation_form: set form for the send confirmation view
+ :param passwordless_login_form: set form for the passwordless login view
+ :param two_factor_setup_form: set form for the 2FA setup view
+ :param two_factor_verify_code_form: set form the the 2FA verify code view
+ :param two_factor_rescue_form: set form for the 2FA rescue view
+ :param two_factor_select_form: set form for selecting between active 2FA methods
+ :param mf_recovery_codes_form: set form for retrieving and setting recovery codes
+ :param mf_recovery_form: set form for multi factor recovery
+ :param us_signin_form: set form for the unified sign in view
+ :param us_setup_form: set form for the unified sign in setup view
+ :param us_setup_validate_form: set form for the unified sign in setup validate view
+ :param us_verify_form: set form for re-authenticating due to freshness check
+ :param wan_register_form: set form for registering a webauthn security key
+ :param wan_register_response_form: set form for registering a webauthn security key
+ :param wan_signin_form: set form for authenticating with a webauthn security key
+ :param wan_signin_response_form: set form for authenticating with a webauthn
+ :param wan_delete_form: set form for deleting a webauthn security key
+ :param wan_verify_form: set form for using a webauthn key to verify authenticity
+ :param mail_util_cls: Class to use for sending emails. Defaults to :class:`MailUtil`
+ :param password_util_cls: Class to use for password normalization/validation.
+ Defaults to :class:`PasswordUtil`
+ :param phone_util_cls: Class to use for phone number utilities.
+ Defaults to :class:`PhoneUtil`
+ :param render_template: function to use to render templates. The default is Flask's
+ render_template() function.
+ :param totp_cls: Class to use as TOTP factory. Defaults to :class:`Totp`
+ :param username_util_cls: Class to use for normalizing and validating usernames.
+ Defaults to :class:`UsernameUtil`
+ :param webauthn_util_cls: Class to use for customizing WebAuthn registration
+ and signin. Defaults to :class:`WebauthnUtil`
+ :param mf_recovery_codes_util_cls: Class for generating, checking, encrypting
+ and decrypting recovery codes. Defaults to :class:`MfRecoveryCodesUtil`
+ :param oauth: An instance of authlib.integrations.flask_client.OAuth. If not set,
+ Flask-Security will create one.
+
+ .. tip::
+ Be sure that all your configuration values have been set PRIOR to
+ instantiating this class. Some configuration values are set as attributes
+ on the instance and therefore won't track any changes.
+
+ .. versionadded:: 3.4.0
+ ``verify_form`` added as part of freshness/re-authentication
+
+ .. versionadded:: 3.4.0
+ ``us_signin_form``, ``us_setup_form``, ``us_setup_validate_form``, and
+ ``us_verify_form`` added as part of the :ref:`unified-sign-in` feature.
+
+ .. versionadded:: 3.4.0
+ ``totp_cls`` added to enable applications to implement replay protection - see
+ :py:class:`Totp`.
+
+ .. versionadded:: 3.4.0
+ ``phone_util_cls`` added to allow different phone number
+ parsing implementations - see :py:class:`PhoneUtil`
+
+ .. versionadded:: 4.0.0
+ ``mail_util_cls`` added to isolate mailing handling.
+ ``password_util_cls`` added to encapsulate password validation/normalization.
+
+ .. versionadded:: 4.1.0
+ ``username_util_cls`` added to encapsulate username handling.
+
+ .. versionadded:: 5.0.0
+ ``wan_register_form``, ``wan_register_response_form``,
+ ``webauthn_signin_form``, ``wan_signin_response_form``,
+ ``webauthn_delete_form``, ``webauthn_verify_form``, ``tf_select_form``.
+ .. versionadded:: 5.0.0
+ ``WebauthnUtil`` class.
+ .. versionadded:: 5.0.0
+ Added support for multi-factor recovery codes ``mf_recovery_codes_form``,
+ ``mf_recovery_form``.
+ .. versionadded:: 5.1.0
+ ``mf_recovery_codes_util_cls``, ``oauth``
+
+ .. deprecated:: 4.0.0
+ ``send_mail`` and ``send_mail_task``. Replaced with ``mail_util_cls``.
+ ``two_factor_verify_password_form`` removed.
+ ``password_validator`` removed in favor of the new ``password_util_cls``.
+ .. deprecated:: 5.0.0
+ Passing in a LoginManager instance. Removed in 5.1.0
+ .. deprecated:: 5.0.0
+ json_encoder_cls is no longer honored since Flask 2.2 has deprecated it.
+ .. deprecated:: 5.3.1
+ Passing in an anonymous_user class. Removed in 5.4.0
+ """
+
+ def __init__(
+ self,
+ app: flask.Flask | None = None,
+ datastore: UserDatastore | None = None,
+ register_blueprint: bool = True,
+ login_form: t.Type[LoginForm] = LoginForm,
+ verify_form: t.Type[VerifyForm] = VerifyForm,
+ confirm_register_form: t.Type[ConfirmRegisterForm] = ConfirmRegisterForm,
+ register_form: t.Type[RegisterForm] = RegisterForm,
+ forgot_password_form: t.Type[ForgotPasswordForm] = ForgotPasswordForm,
+ reset_password_form: t.Type[ResetPasswordForm] = ResetPasswordForm,
+ change_password_form: t.Type[ChangePasswordForm] = ChangePasswordForm,
+ send_confirmation_form: t.Type[SendConfirmationForm] = SendConfirmationForm,
+ passwordless_login_form: t.Type[PasswordlessLoginForm] = PasswordlessLoginForm,
+ two_factor_verify_code_form: t.Type[
+ TwoFactorVerifyCodeForm
+ ] = TwoFactorVerifyCodeForm,
+ two_factor_setup_form: t.Type[TwoFactorSetupForm] = TwoFactorSetupForm,
+ two_factor_rescue_form: t.Type[TwoFactorRescueForm] = TwoFactorRescueForm,
+ two_factor_select_form: t.Type[TwoFactorSelectForm] = TwoFactorSelectForm,
+ mf_recovery_codes_form: t.Type[MfRecoveryCodesForm] = MfRecoveryCodesForm,
+ mf_recovery_form: t.Type[MfRecoveryForm] = MfRecoveryForm,
+ us_signin_form: t.Type[UnifiedSigninForm] = UnifiedSigninForm,
+ us_setup_form: t.Type[UnifiedSigninSetupForm] = UnifiedSigninSetupForm,
+ us_setup_validate_form: t.Type[
+ UnifiedSigninSetupValidateForm
+ ] = UnifiedSigninSetupValidateForm,
+ us_verify_form: t.Type[UnifiedVerifyForm] = UnifiedVerifyForm,
+ wan_register_form: t.Type[WebAuthnRegisterForm] = WebAuthnRegisterForm,
+ wan_register_response_form: t.Type[
+ WebAuthnRegisterResponseForm
+ ] = WebAuthnRegisterResponseForm,
+ wan_signin_form: t.Type[WebAuthnSigninForm] = WebAuthnSigninForm,
+ wan_signin_response_form: t.Type[
+ WebAuthnSigninResponseForm
+ ] = WebAuthnSigninResponseForm,
+ wan_delete_form: t.Type[WebAuthnDeleteForm] = WebAuthnDeleteForm,
+ wan_verify_form: t.Type[WebAuthnVerifyForm] = WebAuthnVerifyForm,
+ mail_util_cls: t.Type[MailUtil] = MailUtil,
+ password_util_cls: t.Type[PasswordUtil] = PasswordUtil,
+ phone_util_cls: t.Type[PhoneUtil] = PhoneUtil,
+ render_template: t.Callable[..., str] = default_render_template,
+ totp_cls: t.Type[Totp] = Totp,
+ username_util_cls: t.Type[UsernameUtil] = UsernameUtil,
+ webauthn_util_cls: t.Type[WebauthnUtil] = WebauthnUtil,
+ mf_recovery_codes_util_cls: t.Type[MfRecoveryCodesUtil] = MfRecoveryCodesUtil,
+ oauth: OAuth | None = None,
+ **kwargs: t.Any,
+ ):
+ # to be nice and hopefully avoid backwards compat issues - we still accept
+ # kwargs - but we don't do anything with them. If caller sends in some -
+ # output a deprecation warning
+ if len(kwargs) > 0:
+ warnings.warn(
+ "kwargs passed to the constructor are now ignored",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self.app = app
+ self._datastore = datastore
+ self._register_blueprint = register_blueprint
+ self.mail_util_cls = mail_util_cls
+ self.password_util_cls = password_util_cls
+ self.phone_util_cls = phone_util_cls
+ self.render_template = render_template
+ self.totp_cls = totp_cls
+ self.username_util_cls = username_util_cls
+ self.webauthn_util_cls = webauthn_util_cls
+ self.mf_recovery_codes_util_cls = mf_recovery_codes_util_cls
+ self._oauth = oauth
+
+ # Forms - we create a list from constructor.
+ # BC - in init_app we will allow override of class.
+ self.forms = {
+ "login_form": FormInfo(cls=login_form),
+ "verify_form": FormInfo(cls=verify_form),
+ "confirm_register_form": FormInfo(cls=confirm_register_form),
+ "register_form": FormInfo(cls=register_form),
+ "forgot_password_form": FormInfo(cls=forgot_password_form),
+ "reset_password_form": FormInfo(cls=reset_password_form),
+ "change_password_form": FormInfo(cls=change_password_form),
+ "send_confirmation_form": FormInfo(cls=send_confirmation_form),
+ "passwordless_login_form": FormInfo(cls=passwordless_login_form),
+ "two_factor_verify_code_form": FormInfo(cls=two_factor_verify_code_form),
+ "two_factor_setup_form": FormInfo(cls=two_factor_setup_form),
+ "two_factor_rescue_form": FormInfo(cls=two_factor_rescue_form),
+ "two_factor_select_form": FormInfo(cls=two_factor_select_form),
+ "mf_recovery_codes_form": FormInfo(cls=mf_recovery_codes_form),
+ "mf_recovery_form": FormInfo(cls=mf_recovery_form),
+ "us_signin_form": FormInfo(cls=us_signin_form),
+ "us_setup_form": FormInfo(cls=us_setup_form),
+ "us_setup_validate_form": FormInfo(cls=us_setup_validate_form),
+ "us_verify_form": FormInfo(cls=us_verify_form),
+ "wan_register_form": FormInfo(cls=wan_register_form),
+ "wan_register_response_form": FormInfo(cls=wan_register_response_form),
+ "wan_signin_form": FormInfo(cls=wan_signin_form),
+ "wan_signin_response_form": FormInfo(cls=wan_signin_response_form),
+ "wan_delete_form": FormInfo(cls=wan_delete_form),
+ "wan_verify_form": FormInfo(cls=wan_verify_form),
+ }
+
+ # Attributes not settable from init.
+ self._unauthn_handler: t.Callable[..., ResponseValue] = default_unauthn_handler
+ self._reauthn_handler: t.Callable[[timedelta, timedelta], ResponseValue] = (
+ default_reauthn_handler
+ )
+ self._unauthz_handler: t.Callable[[str, list[str] | None], ResponseValue] = (
+ default_unauthz_handler
+ )
+ self._render_json: t.Callable[
+ [dict[str, t.Any], int, dict[str, str] | None, User | None],
+ ResponseValue,
+ ] = default_render_json
+ self._want_json: t.Callable[[Request], bool] = default_want_json
+
+ # Type attributes that we don't initialize until init_app time.
+ self.remember_token_serializer: URLSafeTimedSerializer
+ self.login_serializer: URLSafeTimedSerializer
+ self.reset_serializer: URLSafeTimedSerializer
+ self.confirm_serializer: URLSafeTimedSerializer
+ self.us_setup_serializer: URLSafeTimedSerializer
+ self.tf_validity_serializer: URLSafeTimedSerializer
+ self.wan_serializer: URLSafeTimedSerializer
+ self.principal: Principal
+ self.pwd_context: CryptContext
+ self.hashing_context: CryptContext
+ self._context_processors: dict[str, list[t.Callable[[], dict[str, t.Any]]]] = {}
+ self.i18n_domain: FsDomain
+ self.datastore: UserDatastore
+ self.register_blueprint: bool
+ self.two_factor_plugins: TfPlugin
+ self.oauthglue: OAuthGlue | None = None
+ self.datetime_factory: t.Callable[[], datetime] = (
+ naive_utcnow # can be changed in init_app()
+ )
+
+ self.login_manager: flask_login.LoginManager
+ self._mail_util: MailUtil
+ self._phone_util: PhoneUtil
+ self._password_util: PasswordUtil
+ self._totp_factory: Totp
+ self._username_util: UsernameUtil
+ self._mf_recovery_codes_util: MfRecoveryCodesUtil
+
+ # Add necessary attributes here to keep mypy happy
+ self.trackable: bool = False
+ self.confirmable: bool = False
+ self.registerable: bool = False
+ self.changeable: bool = False
+ self.recoverable: bool = False
+ self.two_factor: bool = False
+ self.unified_signin: bool = False
+ self.passwordless: bool = False
+ self.webauthn: bool = False
+
+ self.support_mfa: bool = False
+
+ if app is not None and datastore is not None:
+ self.init_app(app, datastore, register_blueprint=register_blueprint)
+
+ def init_app(
+ self,
+ app: flask.Flask,
+ datastore: UserDatastore | None = None,
+ register_blueprint: bool | None = None,
+ **kwargs: t.Any,
+ ) -> None:
+ """Initializes the Flask-Security extension for the specified
+ application and datastore implementation.
+
+ :param app: The application.
+ :param datastore: An instance of a user datastore.
+ :param register_blueprint: to register the Security blueprint or not.
+ :param kwargs: Can be used to override/initialize any of the form names,
+ flags, and utility classes.
+ All other kwargs are ignored.
+
+ If you create the Security instance with both an 'app' and 'datastore'
+ you shouldn't call this - it will be called as part of the constructor.
+ """
+ self.app = app
+
+ if datastore:
+ self._datastore = datastore
+ if not self._datastore:
+ raise ValueError("Datastore must be provided")
+ self.datastore = self._datastore
+
+ if register_blueprint is not None:
+ self._register_blueprint = register_blueprint
+ self.register_blueprint = self._register_blueprint
+
+ # default post redirects to APPLICATION_ROOT, which itself defaults to "/"
+ app.config.setdefault(
+ "SECURITY_POST_LOGIN_VIEW", app.config.get("APPLICATION_ROOT", "/")
+ )
+ app.config.setdefault(
+ "SECURITY_POST_LOGOUT_VIEW", app.config.get("APPLICATION_ROOT", "/")
+ )
+
+ for key, value in _default_config.items():
+ app.config.setdefault("SECURITY_" + key, value)
+
+ for key, value in _default_messages.items():
+ app.config.setdefault("SECURITY_MSG_" + key, value)
+
+ # Override default forms
+ # BC - kwarg value here overrides init/constructor time
+ # BC - we allow forms to be set from config
+ form_names = [
+ "login_form",
+ "verify_form",
+ "confirm_register_form",
+ "register_form",
+ "forgot_password_form",
+ "reset_password_form",
+ "change_password_form",
+ "send_confirmation_form",
+ "passwordless_login_form",
+ "two_factor_verify_code_form",
+ "two_factor_setup_form",
+ "two_factor_rescue_form",
+ "two_factor_select_form",
+ "mf_recovery_form",
+ "mf_recovery_codes_form",
+ "us_signin_form",
+ "us_setup_form",
+ "us_setup_validate_form",
+ "us_verify_form",
+ "wan_register_form",
+ "wan_register_response_form",
+ "wan_signin_form",
+ "wan_signin_response_form",
+ "wan_delete_form",
+ "wan_verify_form",
+ ]
+ for form_name in form_names:
+ if form_cls := kwargs.get(
+ form_name, cv(form_name.upper(), app, strict=False)
+ ):
+ self.forms[form_name].cls = form_cls
+
+ # The following will be set as attributes and initialized from either
+ # kwargs or config.
+ attr_names = [
+ "trackable",
+ "registerable",
+ "confirmable",
+ "changeable",
+ "recoverable",
+ "two_factor",
+ "unified_signin",
+ "passwordless",
+ "webauthn",
+ "mail_util_cls",
+ "password_util_cls",
+ "phone_util_cls",
+ "render_template",
+ "totp_cls",
+ "webauthn_util_cls",
+ "datetime_factory",
+ ]
+ for attr in attr_names:
+ if ov := kwargs.get(attr, cv(attr.upper(), app, strict=False)):
+ setattr(self, attr, ov)
+
+ identity_loaded.connect_via(app)(_on_identity_loaded)
+
+ if hasattr(self.datastore, "user_model") and not hasattr(
+ self.datastore.user_model, "fs_uniquifier"
+ ): # pragma: no cover
+ raise ValueError("User model must contain fs_uniquifier as of 4.0.0")
+
+ # Check for pre-4.0 SECURITY_USER_IDENTITY_ATTRIBUTES format
+ for uia in cv("USER_IDENTITY_ATTRIBUTES", app=app): # pragma: no cover
+ if not isinstance(uia, dict):
+ raise ValueError(
+ "SECURITY_USER_IDENTITY_ATTRIBUTES changed semantics"
+ " in 4.0 - please see release notes."
+ )
+ if len(list(uia.keys())) != 1:
+ raise ValueError(
+ "Each element in SECURITY_USER_IDENTITY_ATTRIBUTES"
+ " must have one and only one key."
+ )
+
+ self.login_manager = _get_login_manager(app, self)
+ self._phone_util = self.phone_util_cls(app)
+ self._mail_util = self.mail_util_cls(app)
+ self._password_util = self.password_util_cls(app)
+ self._username_util = self.username_util_cls(app)
+ self._webauthn_util = self.webauthn_util_cls(app)
+ self._mf_recovery_codes_util = self.mf_recovery_codes_util_cls(app)
+ self.remember_token_serializer = _get_serializer(app, "remember")
+ self.login_serializer = _get_serializer(app, "login")
+ self.reset_serializer = _get_serializer(app, "reset")
+ self.confirm_serializer = _get_serializer(app, "confirm")
+ self.us_setup_serializer = _get_serializer(app, "us_setup")
+ self.tf_validity_serializer = _get_serializer(app, "two_factor_validity")
+ self.wan_serializer = _get_serializer(app, "wan")
+ self.principal = _get_principal(app)
+ self.pwd_context = _get_pwd_context(app)
+ self.hashing_context = _get_hashing_context(app)
+ self.i18n_domain = FsDomain(app)
+
+ if cv("WEBAUTHN", app=app) or cv("TWO_FACTOR", app):
+ self.support_mfa = True
+
+ if cv("PASSWORDLESS", app=app):
+ warnings.warn(
+ "The passwordless feature was deprecated in Version 5.0.0"
+ " and will be removed in the future. Please use the Unified Signin"
+ " feature instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ if cv("AUTO_LOGIN_AFTER_RESET", app=app):
+ warnings.warn(
+ "The auto-login after successful password reset functionality"
+ " has been deprecated and will be removed in a future release.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ if cv("BACKWARDS_COMPAT_UNAUTHN", app=app):
+ warnings.warn(
+ "The BACKWARDS_COMPAT_UNAUTHN configuration variable is"
+ " deprecated as of version 5.4.0 and will be removed in a future"
+ " release.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ if cv("USERNAME_ENABLE", app):
+ if hasattr(self.datastore, "user_model") and not hasattr(
+ self.datastore.user_model, "username"
+ ): # pragma: no cover
+ raise ValueError(
+ "User model must contain 'username' if"
+ " SECURITY_USERNAME_ENABLE is True"
+ )
+ # if not already listed in user identity attributes, add it at the end
+ uialist = []
+ for uia in cv("USER_IDENTITY_ATTRIBUTES", app=app):
+ uialist.append(list(uia.keys())[0])
+ if "username" not in uialist:
+ uias = cv("USER_IDENTITY_ATTRIBUTES", app=app).copy()
+ uias.append(
+ {
+ "username": {
+ "mapper": uia_username_mapper,
+ "case_insensitive": True,
+ }
+ }
+ )
+ app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = uias
+ self.user_identity_attributes = uias
+
+ # Add dynamic fields - probably overkill to check if these are our forms.
+ fcls = self.forms["register_form"].cls
+ if fcls and issubclass(fcls, RegisterFormMixin):
+ fcls.username = get_register_username_field(app)
+ fcls = self.forms["confirm_register_form"].cls
+ if fcls and issubclass(fcls, RegisterFormMixin):
+ fcls.username = get_register_username_field(app)
+ fcls = self.forms["login_form"].cls
+ if fcls and issubclass(fcls, LoginForm):
+ fcls.username = login_username_field
+
+ # initialize two-factor plugins. Note that each implementation likely
+ # has its own feature flag which will control whether it is active or not.
+ self.two_factor_plugins = TfPlugin()
+ for name, impl_class in cv("TWO_FACTOR_IMPLEMENTATIONS", app).items():
+ module_path, class_name = impl_class.rsplit(".", 1)
+ module = importlib.import_module(module_path)
+ self.two_factor_plugins.register_tf_impl(
+ app, name, getattr(module, class_name)
+ )
+
+ if cv("OAUTH_ENABLE", app=app):
+ self.oauthglue = OAuthGlue(app, self._oauth)
+
+ # register our blueprint/endpoints
+ bp = None
+ if self.register_blueprint:
+ bp = create_blueprint(app, self, __name__)
+ self.two_factor_plugins.create_blueprint(app, bp, self)
+ if self.oauthglue:
+ self.oauthglue._create_blueprint(app, bp)
+ app.register_blueprint(bp)
+ app.context_processor(_context_processor)
+
+ if hasattr(app, "cli"):
+ from .cli import users, roles
+
+ if un := cv("CLI_USERS_NAME", app, strict=True):
+ app.cli.add_command(users, un)
+ if rn := cv("CLI_ROLES_NAME", app, strict=True):
+ app.cli.add_command(roles, rn)
+
+ # Migrate from TWO_FACTOR config to generic config.
+ for newc, oldc in [
+ ("SECURITY_SMS_SERVICE", "SECURITY_TWO_FACTOR_SMS_SERVICE"),
+ ("SECURITY_SMS_SERVICE_CONFIG", "SECURITY_TWO_FACTOR_SMS_SERVICE_CONFIG"),
+ ("SECURITY_TOTP_SECRETS", "SECURITY_TWO_FACTOR_SECRET"),
+ ("SECURITY_TOTP_ISSUER", "SECURITY_TWO_FACTOR_URI_SERVICE_NAME"),
+ ]:
+ if not app.config.get(newc, None):
+ app.config[newc] = app.config.get(oldc, None)
+
+ # Alternate/code authentication configuration checks and setup
+ alt_auth = False
+ if cv("UNIFIED_SIGNIN", app=app):
+ alt_auth = True
+ if len(cv("US_ENABLED_METHODS", app=app)) < 1:
+ raise ValueError("Must configure some US_ENABLED_METHODS")
+ if "sms" in cv(
+ "US_ENABLED_METHODS", app=app
+ ) and not get_identity_attribute("us_phone_number", app=app):
+ warnings.warn(
+ "'sms' was enabled in SECURITY_US_ENABLED_METHODS;"
+ " however 'us_phone_number' not configured in"
+ " SECURITY_USER_IDENTITY_ATTRIBUTES",
+ stacklevel=2,
+ )
+ if cv("TWO_FACTOR", app=app):
+ alt_auth = True
+ if len(cv("TWO_FACTOR_ENABLED_METHODS", app=app)) < 1:
+ raise ValueError("Must configure some TWO_FACTOR_ENABLED_METHODS")
+ if cv("MULTI_FACTOR_RECOVERY_CODES", app=app):
+ # These rely on totp to generate
+ alt_auth = True
+
+ if alt_auth:
+ # cryptography is used to encrypt TOTP secrets
+ self._check_modules("cryptography", "TWO_FACTOR or UNIFIED_SIGNIN")
+
+ need_qrcode = (
+ cv("UNIFIED_SIGNIN", app=app)
+ and "authenticator" in cv("US_ENABLED_METHODS", app=app)
+ ) or (
+ cv("TWO_FACTOR", app=app)
+ and "authenticator" in cv("TWO_FACTOR_ENABLED_METHODS", app=app)
+ )
+ if need_qrcode:
+ self._check_modules("qrcode", "TWO_FACTOR or UNIFIED_SIGNIN")
+
+ need_sms = (
+ cv("UNIFIED_SIGNIN", app=app)
+ and "sms" in cv("US_ENABLED_METHODS", app=app)
+ ) or (
+ cv("TWO_FACTOR", app=app)
+ and "sms" in cv("TWO_FACTOR_ENABLED_METHODS", app=app)
+ )
+ if need_sms:
+ sms_service = cv("SMS_SERVICE", app=app)
+ if sms_service == "Twilio": # pragma: no cover
+ self._check_modules("twilio", "SMS")
+ if self.phone_util_cls == PhoneUtil:
+ self._check_modules("phonenumbers", "SMS")
+
+ secrets = cv("TOTP_SECRETS", app=app)
+ issuer = cv("TOTP_ISSUER", app=app)
+ if not secrets or not issuer:
+ raise ValueError("Both TOTP_SECRETS and TOTP_ISSUER must be set")
+ self._totp_factory = self.totp_cls(secrets, issuer)
+
+ if cv("PASSWORD_COMPLEXITY_CHECKER", app=app) == "zxcvbn":
+ self._check_modules("zxcvbn", "PASSWORD_COMPLEXITY_CHECKER")
+
+ if cv("WEBAUTHN", app=app):
+ self._check_modules("webauthn", "WEBAUTHN")
+
+ if cv("USERNAME_ENABLE", app=app):
+ self._check_modules("bleach", "USERNAME_ENABLE")
+
+ # Register so other packages can reference our translations.
+ app.jinja_env.globals["_fsdomain"] = self.i18n_domain.gettext
+
+ # Perform CSRF checks. Apps must initialize CSRFProtect PRIOR to
+ # initializing us.
+ self._csrf_init(app)
+
+ # register our JSON encoder extensions
+ setup_json(app, bp)
+
+ app.extensions["security"] = self
+
+ def _check_modules(self, module, config_name): # pragma: no cover
+ from importlib.util import find_spec
+
+ module_exists = find_spec(module)
+ if not module_exists:
+ raise ValueError(f"{module} is required for {config_name}")
+
+ return module_exists
+
+ @staticmethod
+ def _csrf_init(app):
+ # various config checks - some of these are opinionated in that there
+ # could be a reason for some of these combinations - but in general
+ # they cause strange behavior.
+ # WTF_CSRF_ENABLED defaults to True if not set in Flask-WTF
+ if not app.config.get("WTF_CSRF_ENABLED", True):
+ return
+ csrf = app.extensions.get("csrf", None)
+
+ # If they don't want ALL mechanisms protected, then they must
+ # set WTF_CSRF_CHECK_DEFAULT=False so that our decorators get control.
+ # And our decorators use csrf.protect()
+ if cv("CSRF_PROTECT_MECHANISMS", app=app) != AUTHN_MECHANISMS:
+ if not csrf:
+ # This isn't good.
+ raise ValueError(
+ "CSRF_PROTECT_MECHANISMS defined but"
+ " CsrfProtect not part of application."
+ " Make sure to initialize CSRFProtect prior to"
+ " initializing Flask-Security"
+ )
+ if app.config.get("WTF_CSRF_CHECK_DEFAULT", True):
+ raise ValueError(
+ "WTF_CSRF_CHECK_DEFAULT must be set to False if"
+ " CSRF_PROTECT_MECHANISMS is set"
+ )
+ # We don't get control unless they turn off WTF_CSRF_CHECK_DEFAULT if
+ # they have enabled global CSRFProtect.
+ if (
+ cv("CSRF_IGNORE_UNAUTH_ENDPOINTS", app=app)
+ and csrf
+ and app.config.get("WTF_CSRF_CHECK_DEFAULT", False)
+ ):
+ raise ValueError(
+ "To ignore unauth endpoints you must set WTF_CSRF_CHECK_DEFAULT"
+ " to False"
+ )
+
+ csrf_cookie = cv("CSRF_COOKIE", app=app)
+ # We used to have 'key' part of CSRF_COOKIE - and in csrf_cookie_handler
+ # we removed that prior to setting the cookie. That was a terrible UI
+ # decision since if the user sets the key - they likely will not set
+ # all the other important things like samesite, secure etc.
+ # Now CSRF_COOKIE_NAME is used for the name - we do the backwards compat
+ # magic here
+ if csrf_cookie and csrf_cookie.get("key", None):
+ app.config["SECURITY_CSRF_COOKIE_NAME"] = csrf_cookie.pop("key")
+ if cv("CSRF_COOKIE_NAME", app=app) and not csrf:
+ # Common use case is for cookie value to be used as contents for header
+ # which is only looked at when CsrfProtect is initialized.
+ raise ValueError(
+ "CSRF_COOKIE defined however CsrfProtect not part of application"
+ )
+
+ if csrf:
+ csrf.exempt("flask_security.views.logout")
+ # Add configured header to WTF_CSRF_HEADERS
+ if ch := cv("CSRF_HEADER", app=app):
+ if ch not in app.config["WTF_CSRF_HEADERS"]:
+ app.config["WTF_CSRF_HEADERS"].append(ch)
+ if cv("CSRF_COOKIE_NAME", app=app):
+ app.after_request(csrf_cookie_handler)
+
+ def set_form_info(self, name: str, form_info: FormInfo) -> None:
+ """Set form instantiation info.
+
+ :param name: Name of form.
+ :param form_info: see :py:class:`FormInfo`
+
+ .. admonition:: Advanced
+
+ Forms (which are all FlaskForms) are instantiated at the start of each
+ request. Normally this is done as part of a view by simply calling the
+ form class constructor - Flask-WTForms handles filling it in from
+ various request attributes.
+
+ The form classes themselves can be extended (e.g. to add or change fields)
+ and the derived class can be set at `Security` constructor time,
+ `init_app` time, or using this method.
+
+ This default implementation is suitable for most applications.
+
+ Some application might want to control the instantiation of forms, for
+ example to be able to inject additional validation services.
+ Using this method, a callable `instantiator` can be set that Flask-Security
+ will call to return a properly instantiated form.
+
+ .. danger::
+ Do not perform any validation as part of instantiation - many views have
+ a bunch of logic PRIOR to calling the form validator.
+
+ .. versionadded:: 5.1.0
+ """
+ if name not in self.forms.keys():
+ raise ValueError(f"Unknown form name {name}")
+ if form_info.instantiator == _default_form_instantiator and not form_info.cls:
+ raise ValueError(
+ "If default form instantiator is used, a form class must be provided"
+ )
+ self.forms[name] = form_info
+
+ def render_json(
+ self,
+ cb: t.Callable[
+ [dict[str, t.Any], int, dict[str, str] | None, User | None],
+ ResponseValue,
+ ],
+ ) -> None:
+ """Callback to render response payload as JSON.
+
+ :param cb: Callback function with
+ signature (payload, code, headers=None, user=None)
+
+ :payload: A dict. Please see the formal API spec for details.
+ :code: Http status code
+ :headers: Headers object
+ :user: the UserDatastore object (or None). Note that this is usually
+ the same as current_user - but not always.
+
+ The default implementation simply returns::
+
+ headers["Content-Type"] = "application/json"
+ payload = dict(meta=dict(code=code), response=payload)
+ return make_response(jsonify(payload), code, headers)
+
+ .. important::
+ Note that this has nothing to do with how the response is serialized.
+ That is controlled by Flask and starting with Flask 2.2 that is managed
+ by sub-classing Flask::JSONProvider. Flask-Security does this to add
+ serializing lazy-strings.
+
+
+ This can be used by applications to unify all their JSON API responses.
+ This is called in a request context and should return a Response or something
+ Flask can create a Response from.
+
+ .. versionadded:: 3.3.0
+ """
+ self._render_json = cb
+
+ def want_json(self, fn: t.Callable[[flask.Request], bool]) -> None:
+ """Function that returns True if response should be JSON (based on the request)
+
+ :param fn: Function with the following signature (request)
+
+ :request: Werkzueg/Flask request
+
+ The default implementation returns True if either the Content-Type is
+ "application/json" or the best Accept header value is "application/json".
+
+ .. versionadded:: 3.3.0
+ """
+ self._want_json = fn
+
+ def unauthz_handler(
+ self,
+ cb: t.Callable[[str, list[str] | None], ResponseValue],
+ ) -> None:
+ """
+ Callback for failed authorization.
+ This is called by the :func:`roles_required`, :func:`roles_accepted`,
+ :func:`permissions_required`, or :func:`permissions_accepted`
+ if a role or permission is missing.
+
+ :param cb: Callback function with signature (func, params)
+
+ :func_name: the decorator function name (e.g. 'roles_required')
+ :params: list of what (if any) was passed to the decorator.
+
+ Should return a Response or something Flask can create a Response from.
+ Can raise an exception if it is handled as part of
+ flask.errorhandler()
+
+ With the passed parameters the application could deliver a concise error
+ message.
+
+ .. versionadded:: 3.3.0
+
+ .. versionchanged:: 5.1.0
+ Pass in the function name, not the function!
+ """
+ self._unauthz_handler = cb
+
+ def unauthn_handler(
+ self,
+ cb: t.Callable[[list[str], dict[str, str] | None], ResponseValue],
+ ) -> None:
+ """
+ Callback for failed authentication.
+ This is called by :func:`auth_required`, :func:`auth_token_required`
+ or :func:`http_auth_required` if authentication fails.
+ It is also called from Flask-Login's @login_required decorator.
+
+ :param cb: Callback function with signature (mechanisms=None, headers=None)
+
+ :mechanisms: List of which authentication mechanisms were tried
+ :headers: dict of headers to return
+
+ Should return a Response or something Flask can create a Response from.
+ Can raise an exception if it is handled as part of
+ ``flask.errorhandler()``
+
+ The default implementation will return a 401 response if the request was JSON,
+ otherwise will redirect to the `login` view.
+
+ .. versionadded:: 3.3.0
+
+ .. versionchanged:: 5.4.0
+ No longer calls Flask-Login and has complete logic built-in.
+ """
+ self._unauthn_handler = cb
+
+ def reauthn_handler(
+ self, cb: t.Callable[[timedelta, timedelta], ResponseValue]
+ ) -> None:
+ """
+ Callback when endpoint required a fresh authentication.
+ This is called by :func:`auth_required`.
+
+ :param cb: Callback function with signature (within, grace)
+
+ :within: timedelta that endpoint required fresh authentication within.
+ :grace: timedelta of grace period that endpoint allowed.
+
+ Should return a Response or something Flask can create a Response from.
+ Can raise an exception if it is handled as part of
+ ``flask.errorhandler()``
+
+ The default implementation will return a 401 response if the request was JSON,
+ otherwise will redirect to :py:data:`SECURITY_US_VERIFY_URL`
+ (if :py:data:`SECURITY_UNIFIED_SIGNIN` is enabled)
+ else to :py:data:`SECURITY_VERIFY_URL`.
+ If both of those are None it sends an ``abort(401)``.
+
+ See :meth:`flask_security.auth_required` for details about freshness checking.
+
+ .. versionadded:: 3.4.0
+ """
+ self._reauthn_handler = cb
+
+ def _add_ctx_processor(
+ self, endpoint: str, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ group = self._context_processors.setdefault(endpoint, [])
+ if fn not in group:
+ group.append(fn)
+
+ def _run_ctx_processor(self, endpoint: str) -> dict[str, t.Any]:
+ rv: dict[str, t.Any] = {}
+ for gl in ["global", endpoint]:
+ for fn in self._context_processors.setdefault(gl, []):
+ rv.update(fn())
+ return rv
+
+ def context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("global", fn)
+
+ def forgot_password_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("forgot_password", fn)
+
+ def login_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("login", fn)
+
+ def register_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("register", fn)
+
+ def reset_password_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("reset_password", fn)
+
+ def change_password_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("change_password", fn)
+
+ def send_confirmation_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("send_confirmation", fn)
+
+ def send_login_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("send_login", fn)
+
+ def verify_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("verify", fn)
+
+ def mail_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("mail", fn)
+
+ def tf_setup_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("tf_setup", fn)
+
+ def tf_token_validation_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("tf_token_validation", fn)
+
+ def tf_select_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("tf_select", fn)
+
+ def us_signin_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("us_signin", fn)
+
+ def us_setup_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("us_setup", fn)
+
+ def us_verify_context_processor(self, fn: t.Callable[[], dict[str, t.Any]]) -> None:
+ self._add_ctx_processor("us_verify", fn)
+
+ def wan_register_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("wan_register", fn)
+
+ def wan_signin_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("wan_signin", fn)
+
+ def wan_verify_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("wan_verify", fn)
+
+ def mf_recovery_codes_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("mf_recovery_codes", fn)
+
+ def mf_recovery_context_processor(
+ self, fn: t.Callable[[], dict[str, t.Any]]
+ ) -> None:
+ self._add_ctx_processor("mf_recovery", fn)
diff --git a/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/datastore.py b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/datastore.py
new file mode 100644
index 0000000000000000000000000000000000000000..1445375d5858dfcb4335c598a08c7906254a09ff
--- /dev/null
+++ b/pgsql/pgAdmin 4/python/Lib/site-packages/flask_security/datastore.py
@@ -0,0 +1,1202 @@
+"""
+ flask_security.datastore
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+
+ This module contains an user datastore classes.
+
+ :copyright: (c) 2012 by Matt Wright.
+ :copyright: (c) 2019-2024 by J. Christopher Wagner (jwag).
+ :license: MIT, see LICENSE for more details.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+import json
+import typing as t
+import uuid
+from copy import copy
+
+from .utils import config_value as cv
+
+if t.TYPE_CHECKING: # pragma: no cover
+ import flask_sqlalchemy
+ import mongoengine
+ import sqlalchemy.orm.scoping
+
+
+class Datastore:
+ def __init__(self, db):
+ self.db = db
+
+ def commit(self):
+ pass
+
+ def put(self, model):
+ raise NotImplementedError
+
+ def delete(self, model):
+ raise NotImplementedError
+
+
+try:
+ import sqlalchemy.types as types
+
+ class AsaList(types.TypeDecorator):
+ """
+ SQL-like DBs don't have a List type - so do that here by converting to a comma
+ separate string.
+ For SQLAlchemy-based datastores, this can be used as::
+
+ Column(MutableList.as_mutable(AsaList()), nullable=True)
+ """
+
+ impl = types.UnicodeText
+
+ def process_bind_param(self, value, dialect):
+ # produce a string from an iterable
+ try:
+ return ",".join(value)
+ except TypeError:
+ return value
+
+ def process_result_value(self, value, dialect):
+ if value:
+ return value.split(",")
+ return []
+
+except ImportError: # pragma: no cover
+
+ class AsaList: # type: ignore
+ """
+ SQL-like DBs don't have a List type - so do that here by converting to a comma
+ separate string.
+ For SQLAlchemy-based datastores, this can be used as::
+
+ Column(MutableList.as_mutable(AsaList()), nullable=True)
+ """
+
+ pass
+
+
+class SQLAlchemyDatastore(Datastore):
+ def commit(self):
+ self.db.session.commit()
+
+ def put(self, model):
+ self.db.session.add(model)
+ return model
+
+ def delete(self, model):
+ self.db.session.delete(model)
+
+
+class MongoEngineDatastore(Datastore):
+ def put(self, model):
+ model.save()
+ return model
+
+ def delete(self, model):
+ model.delete()
+
+
+class PeeweeDatastore(Datastore):
+ def put(self, model):
+ model.save()
+ return model
+
+ def delete(self, model):
+ model.delete_instance(recursive=True)
+
+
+def with_pony_session(f):
+ from functools import wraps
+
+ @wraps(f)
+ def decorator(*args, **kwargs):
+ from pony.orm import db_session
+ from pony.orm.core import local
+ from flask import (
+ after_this_request,
+ current_app,
+ has_app_context,
+ has_request_context,
+ )
+ from flask.signals import appcontext_popped
+
+ register = local.db_context_counter == 0
+ if register and (has_app_context() or has_request_context()):
+ db_session.__enter__()
+
+ result = f(*args, **kwargs)
+
+ if register:
+ if has_request_context():
+
+ @after_this_request
+ def pop(request):
+ db_session.__exit__()
+ return request
+
+ elif has_app_context():
+
+ @appcontext_popped.connect_via(current_app._get_current_object())
+ def pop(sender, *args, **kwargs):
+ while local.db_context_counter:
+ db_session.__exit__()
+
+ else:
+ raise RuntimeError("Needs app or request context")
+ return result
+
+ return decorator
+
+
+class PonyDatastore(Datastore):
+ def commit(self):
+ self.db.commit()
+
+ @with_pony_session
+ def put(self, model):
+ return model
+
+ @with_pony_session
+ def delete(self, model):
+ model.delete()
+
+
+class UserDatastore:
+ """Abstracted user datastore.
+
+ :param user_model: A user model class definition
+ :param role_model: A role model class definition
+ :param webauthn_model: A model used to store webauthn registrations
+
+ .. important::
+ For mutating operations, the user/role will be added to the
+ datastore (by calling self.put(