示例#1
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))
    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}, runtime: {}'.format(QT_VERSION_STR, qVersion()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
    ]
    lines += _module_versions()

    if QSslSocket is not None and QSslSocket.supportsSsl():
        ssl_version = QSslSocket.sslLibraryVersionString()
    else:
        ssl_version = 'unavailable'
    lines += [
        'Webkit: {}'.format(qWebKitVersion()),
        'Harfbuzz: {}'.format(os.environ.get('QT_HARFBUZZ', 'system')),
        'SSL: {}'.format(ssl_version),
        '',
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
    ]
    lines += _os_info()
    return '\n'.join(lines)
示例#2
0
def init():
    """Disable insecure SSL ciphers on old Qt versions."""
    if not qtutils.version_check("5.3.0"):
        # Disable weak SSL ciphers.
        # See https://codereview.qt-project.org/#/c/75943/
        good_ciphers = [c for c in QSslSocket.supportedCiphers() if c.usedBits() >= 128]
        QSslSocket.setDefaultCiphers(good_ciphers)
def init():
    """Disable insecure SSL ciphers on old Qt versions."""
    default_ciphers = QSslSocket.defaultCiphers()
    log.init.debug("Default Qt ciphers: {}".format(
        ', '.join(c.name() for c in default_ciphers)))

    good_ciphers = []
    bad_ciphers = []
    for cipher in default_ciphers:
        if _is_secure_cipher(cipher):
            good_ciphers.append(cipher)
        else:
            bad_ciphers.append(cipher)

    log.init.debug("Disabling bad ciphers: {}".format(
        ', '.join(c.name() for c in bad_ciphers)))
    QSslSocket.setDefaultCiphers(good_ciphers)
示例#4
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    if qVersion() != QT_VERSION_STR:
        qt_version = 'Qt: {} (compiled {})'.format(qVersion(), QT_VERSION_STR)
    else:
        qt_version = 'Qt: {}'.format(qVersion())

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        qt_version,
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += _module_versions()

    lines += ['pdf.js: {}'.format(_pdfjs_version())]

    if qWebKitVersion is None:
        lines.append('Webkit: no')
    else:
        lines.append('Webkit: {}'.format(qWebKitVersion()))

    lines += [
        'SSL: {}'.format(QSslSocket.sslLibraryVersionString()),
        '',
    ]

    qapp = QApplication.instance()
    if qapp:
        style = qapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
    ]
    lines += _os_info()

    lines += [
        '',
        'Paths:',
    ]
    for name, path in _path_info().items():
        lines += ['{}: {}'.format(name, path)]

    return '\n'.join(lines)
示例#5
0
def initSSL():
    """
    Function to initialize some global SSL stuff.
    """
    blacklist = [
        "SRP-AES-256-CBC-SHA",          # open to MitM
        "SRP-AES-128-CBC-SHA",          # open to MitM
    ]
    
    try:
        from PyQt5.QtNetwork import QSslSocket
    except ImportError:
        # no SSL available, so there is nothing to initialize
        return
    
    strongCiphers = [c for c in QSslSocket.supportedCiphers()
                     if c.name() not in blacklist and c.usedBits() >= 128]
    QSslSocket.setDefaultCiphers(strongCiphers)
示例#6
0
 def __getSystemCaCertificates(self):
     """
     Private method to get the list of system certificates.
     
     @return list of system certificates (list of QSslCertificate)
     """
     caList = QSslCertificate.fromData(Globals.toByteArray(
         Preferences.Prefs.settings.value("Ssl/SystemCertificates")))
     if not caList:
         caList = QSslSocket.systemCaCertificates()
     return caList
示例#7
0
def check_ssl_support():
    """Check if SSL support is available."""
    try:
        from PyQt5.QtNetwork import QSslSocket
    except ImportError:
        ok = False
    else:
        ok = QSslSocket.supportsSsl()
    if not ok:
        text = "Fatal error: Your Qt is built without SSL support."
        _die(text)
示例#8
0
def init():
    """Disable insecure SSL ciphers on old Qt versions."""
    if qtutils.version_check("5.3.0"):
        default_ciphers = QSslSocket.defaultCiphers()
        log.init.debug("Default Qt ciphers: {}".format(", ".join(c.name() for c in default_ciphers)))
    else:
        # https://codereview.qt-project.org/#/c/75943/
        default_ciphers = QSslSocket.supportedCiphers()
        log.init.debug("Supported Qt ciphers: {}".format(", ".join(c.name() for c in default_ciphers)))

    good_ciphers = []
    bad_ciphers = []
    for cipher in default_ciphers:
        if _is_secure_cipher(cipher):
            good_ciphers.append(cipher)
        else:
            bad_ciphers.append(cipher)

    log.init.debug("Disabling bad ciphers: {}".format(", ".join(c.name() for c in bad_ciphers)))
    QSslSocket.setDefaultCiphers(good_ciphers)
示例#9
0
def check_backend_ssl_support(backend):
    """Check for full SSL availability when we know the backend."""
    from PyQt5.QtNetwork import QSslSocket
    from qutebrowser.utils import log, usertypes
    text = ("Could not initialize QtNetwork SSL support. If you use "
            "OpenSSL 1.1 with a PyQt package from PyPI (e.g. on Archlinux "
            "or Debian Stretch), you need to set LD_LIBRARY_PATH to the path "
            "of OpenSSL 1.0. This only affects downloads.")

    if not QSslSocket.supportsSsl():
        if backend == usertypes.Backend.QtWebKit:
            _die("Could not initialize SSL support.")
        else:
            assert backend == usertypes.Backend.QtWebEngine
            log.init.warning(text)
示例#10
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    if qVersion() != QT_VERSION_STR:
        qt_version = "Qt: {} (compiled {})".format(qVersion(), QT_VERSION_STR)
    else:
        qt_version = "Qt: {}".format(qVersion())

    lines += [
        "",
        "{}: {}".format(platform.python_implementation(), platform.python_version()),
        qt_version,
        "PyQt: {}".format(PYQT_VERSION_STR),
        "",
    ]

    lines += _module_versions()

    lines += ["pdf.js: {}".format(_pdfjs_version())]

    if qWebKitVersion is None:
        lines.append("Webkit: no")
    else:
        lines.append("Webkit: {}".format(qWebKitVersion()))

    lines += ["SSL: {}".format(QSslSocket.sslLibraryVersionString()), ""]

    qapp = QApplication.instance()
    if qapp:
        style = qapp.style()
        lines.append("Style: {}".format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        "Platform: {}, {}".format(platform.platform(), platform.architecture()[0]),
        "Frozen: {}".format(hasattr(sys, "frozen")),
        "Imported from {}".format(importpath),
    ]
    lines += _os_info()
    return "\n".join(lines)
示例#11
0
    def handle(self, argv: List[str]) -> int:
        """ Parse options, setup logs and manager and dispatch execution. """

        # Pre-configure the logging to catch early errors
        configure(console_level="DEBUG", command_name="early")

        options = self.parse_cli(argv)

        if hasattr(options, "local_folder"):
            options.local_folder = normalize_and_expand_path(options.local_folder)
        if hasattr(options, "nxdrive_home"):
            options.nxdrive_home = normalize_and_expand_path(options.nxdrive_home)

        command = getattr(options, "command", "launch")
        handler = getattr(self, command, None)
        if not handler:
            raise RuntimeError(f"No handler implemented for command {command}")

        self._configure_logger(command, options)

        log.info(f"Command line: argv={argv!r}, options={options!r}")
        log.info(f"Running on version {self.get_version()}")

        if QSslSocket:
            has_ssl_support = QSslSocket.supportsSsl()
            log.info(f"SSL support: {has_ssl_support!r}")
            if not has_ssl_support:
                if Options.is_frozen:
                    raise RuntimeError("No SSL support, packaging must have failed.")
                else:
                    options.ca_bundle = None
                    options.ssl_no_verify = True

        # We cannot use fail_on_error=True because options is a namespace
        # and contains a lot of inexistant Options values.
        Options.update(options, setter="cli", fail_on_error=False)

        if command != "uninstall":
            self._install_faulthandler()
            self.manager = self.get_manager()

        return handler(options)
示例#12
0
def version(short=False):
    """Return a string with various version informations.

    Args:
        short: Return a shortened output.
    """
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))
    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}, runtime: {}'.format(QT_VERSION_STR, qVersion()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
    ]

    if not short:
        style = QApplication.instance().style()
        lines += [
            'Style: {}'.format(style.metaObject().className()),
            'Desktop: {}'.format(os.environ.get('DESKTOP_SESSION')),
        ]

        lines += _module_versions()

        lines += [
            'pdf.js: {}'.format(_pdfjs_version()),
            'Webkit: {}'.format(qWebKitVersion()),
            'Harfbuzz: {}'.format(os.environ.get('QT_HARFBUZZ', 'system')),
            'SSL: {}'.format(QSslSocket.sslLibraryVersionString()),
            '',
            'Frozen: {}'.format(hasattr(sys, 'frozen')),
            'Platform: {}, {}'.format(platform.platform(),
                                      platform.architecture()[0]),
        ]
        lines += _os_info()
    return '\n'.join(lines)
示例#13
0
def check_ssl_support(backend):
    """Check if SSL support is available."""
    from qutebrowser.utils import log

    try:
        from PyQt5.QtNetwork import QSslSocket
    except ImportError:
        _die("Fatal error: Your Qt is built without SSL support.")

    text = ("Could not initialize QtNetwork SSL support. If you use "
            "OpenSSL 1.1 with a PyQt package from PyPI (e.g. on Archlinux "
            "or Debian Stretch), you need to set LD_LIBRARY_PATH to the path "
            "of OpenSSL 1.0.")
    if backend == 'webengine':
        text += " This only affects downloads."

    if not QSslSocket.supportsSsl():
        if backend == 'webkit':
            _die("Could not initialize SSL support.")
        else:
            assert backend == 'webengine'
            log.init.warning(text)
示例#14
0
def version(short=False):
    """Return a string with various version informations.

    Args:
        short: Return a shortened output.
    """
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))
    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}, runtime: {}'.format(QT_VERSION_STR, qVersion()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
    ]

    if not short:
        style = QApplication.instance().style()
        lines += [
            'Style: {}'.format(style.metaObject().className()),
            'Desktop: {}'.format(os.environ.get('DESKTOP_SESSION')),
        ]

        lines += _module_versions()

        lines += [
            'pdf.js: {}'.format(_pdfjs_version()),
            'Webkit: {}'.format(qWebKitVersion()),
            'Harfbuzz: {}'.format(os.environ.get('QT_HARFBUZZ', 'system')),
            'SSL: {}'.format(QSslSocket.sslLibraryVersionString()),
            '',
            'Frozen: {}'.format(hasattr(sys, 'frozen')),
            'Platform: {}, {}'.format(platform.platform(),
                                      platform.architecture()[0]),
        ]
        lines += _os_info()
    return '\n'.join(lines)
示例#15
0
def _handle_ssl_support(fatal=False):
    """Check for full SSL availability.

    If "fatal" is given, show an error and exit.
    """
    text = ("Could not initialize QtNetwork SSL support. If you use "
            "OpenSSL 1.1 with a PyQt package from PyPI (e.g. on Archlinux "
            "or Debian Stretch), you need to set LD_LIBRARY_PATH to the path "
            "of OpenSSL 1.0. This only affects downloads.")

    if QSslSocket.supportsSsl():
        return

    if fatal:
        errbox = msgbox.msgbox(parent=None,
                               title="SSL error",
                               text="Could not initialize SSL support.",
                               icon=QMessageBox.Critical,
                               plain_text=False)
        errbox.exec_()
        sys.exit(usertypes.Exit.err_init)

    assert not fatal
    log.init.warning(text)
示例#16
0
    def _handle_ssl_support(self, fatal: bool = False) -> None:
        """Check for full SSL availability.

        If "fatal" is given, show an error and exit.
        """
        text = ("Could not initialize QtNetwork SSL support. If you use "
                "OpenSSL 1.1 with a PyQt package from PyPI (e.g. on Archlinux "
                "or Debian Stretch), you need to set LD_LIBRARY_PATH to the "
                "path of OpenSSL 1.0. This only affects downloads.")

        if QSslSocket.supportsSsl():
            return

        if fatal:
            errbox = msgbox.msgbox(parent=None,
                                   title="SSL error",
                                   text="Could not initialize SSL support.",
                                   icon=QMessageBox.Critical,
                                   plain_text=False)
            errbox.exec_()
            sys.exit(usertypes.Exit.err_init)

        assert not fatal
        log.init.warning(text)
示例#17
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    backend = objects.backend.name
    if (qWebKitVersion is not None
            and objects.backend == usertypes.Backend.QtWebKit
            and qtutils.is_qtwebkit_ng(qWebKitVersion())):
        backend = 'QtWebKit-NG'
    lines.append("Backend: {}".format(backend))

    if qVersion() != QT_VERSION_STR:
        qt_version = 'Qt: {} (compiled {})'.format(qVersion(), QT_VERSION_STR)
    else:
        qt_version = 'Qt: {}'.format(qVersion())

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        qt_version,
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += _module_versions()

    lines += ['pdf.js: {}'.format(_pdfjs_version())]

    if qWebKitVersion is None:
        lines.append('Webkit: no')
    else:
        lines.append('Webkit: {}'.format(qWebKitVersion()))

    lines += [
        'SSL: {}'.format(QSslSocket.sslLibraryVersionString()),
        '',
    ]

    qapp = QApplication.instance()
    if qapp:
        style = qapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
    ]
    lines += _os_info()

    lines += [
        '',
        'Paths:',
    ]
    for name, path in _path_info().items():
        lines += ['{}: {}'.format(name, path)]

    return '\n'.join(lines)
示例#18
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.

"""Our own QNetworkAccessManager."""

from PyQt5.QtCore import pyqtSlot, pyqtSignal, PYQT_VERSION, QCoreApplication
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply

try:
    from PyQt5.QtNetwork import QSslSocket
except ImportError:
    SSL_AVAILABLE = False
else:
    SSL_AVAILABLE = QSslSocket.supportsSsl()

from qutebrowser.config import config
from qutebrowser.utils import message, log, usertypes, utils, objreg
from qutebrowser.browser import cookies
from qutebrowser.browser.network import qutescheme, networkreply


HOSTBLOCK_ERROR_STRING = '%HOSTBLOCK%'


class NetworkManager(QNetworkAccessManager):

    """Our own QNetworkAccessManager.

    Attributes:
示例#19
0
    qVersion,
)
from PyQt5.QtNetwork import QSslSocket

from picard import PICARD_FANCY_VERSION_STR
from picard.disc import discid_version
from picard.util.astrcmp import astrcmp_implementation

_versions = OrderedDict([("version", PICARD_FANCY_VERSION_STR),
                         ("python-version", python_version()),
                         ("pyqt-version", pyqt_version),
                         ("qt-version", qVersion()),
                         ("mutagen-version", mutagen_version),
                         ("discid-version", discid_version),
                         ("astrcmp", astrcmp_implementation),
                         ("ssl-version", QSslSocket.sslLibraryVersionString())
                         ])

_names = {
    "version": "Picard",
    "python-version": "Python",
    "pyqt-version": "PyQt",
    "qt-version": "Qt",
    "mutagen-version": "Mutagen",
    "discid-version": "Discid",
    "astrcmp": "astrcmp",
    "ssl-version": "SSL",
}


def _value_as_text(value, i18n=False):
示例#20
0
文件: versions.py 项目: mineo/picard
)
from PyQt5.QtNetwork import QSslSocket

from picard import PICARD_FANCY_VERSION_STR
from picard.disc import discid_version
from picard.util.astrcmp import astrcmp_implementation

_versions = OrderedDict([
    ("version", PICARD_FANCY_VERSION_STR),
    ("python-version", python_version()),
    ("pyqt-version", pyqt_version),
    ("qt-version", QT_VERSION_STR),
    ("mutagen-version", mutagen_version),
    ("discid-version", discid_version),
    ("astrcmp", astrcmp_implementation),
    ("SSL", QSslSocket.sslLibraryVersionString())
])

_names = {
    "version": "Picard",
    "python-version": "Python",
    "pyqt-version": "PyQt",
    "qt-version": "Qt",
    "mutagen-version": "Mutagen",
    "discid-version": "Discid",
    "astrcmp": "astrcmp",
    "SSL": "SSL",
}


def _value_as_text(value, i18n=False):
示例#21
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    lines.append("Backend: {}".format(_backend()))

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}'.format(earlyinit.qt_version()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += _module_versions()

    lines += [
        'pdf.js: {}'.format(_pdfjs_version()),
        'sqlite: {}'.format(sql.version()),
        'QtNetwork SSL: {}\n'.format(QSslSocket.sslLibraryVersionString()
                                     if QSslSocket.supportsSsl() else 'no'),
    ]

    qapp = QApplication.instance()
    if qapp:
        style = qapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
    ]
    dist = distribution()
    if dist is not None:
        lines += [
            'Linux distribution: {} ({})'.format(dist.pretty, dist.parsed.name)
        ]

    lines += [
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
        "Qt library executable path: {}, data path: {}".format(
            QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath),
            QLibraryInfo.location(QLibraryInfo.DataPath)
        )
    ]

    if not dist or dist.parsed == Distribution.unknown:
        lines += _os_info()

    lines += [
        '',
        'Paths:',
    ]
    for name, path in sorted(_path_info().items()):
        lines += ['{}: {}'.format(name, path)]

    return '\n'.join(lines)
示例#22
0
def version():
    """Return a string with various version informations."""
    lines = ["qutebrowser v{}".format(qutebrowser.__version__)]
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    lines.append("Backend: {}".format(_backend()))

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'Qt: {}'.format(qt_version()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += _module_versions()

    lines += ['pdf.js: {}'.format(_pdfjs_version())]

    lines += [
        'SSL: {}'.format(QSslSocket.sslLibraryVersionString()),
        '',
    ]

    qapp = QApplication.instance()
    if qapp:
        style = qapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
    ]
    dist = distribution()
    if dist is not None:
        lines += [
            'Linux distribution: {} ({})'.format(dist.pretty, dist.parsed.name)
        ]

    lines += [
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
        "Qt library executable path: {}, data path: {}".format(
            QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath),
            QLibraryInfo.location(QLibraryInfo.DataPath))
    ]

    if not dist or dist.parsed == Distribution.unknown:
        lines += _os_info()

    lines += [
        '',
        'Paths:',
    ]
    for name, path in _path_info().items():
        lines += ['{}: {}'.format(name, path)]

    return '\n'.join(lines)
示例#23
0
    QT_VERSION_STR,
)
from PyQt5.QtNetwork import QSslSocket

from picard import PICARD_FANCY_VERSION_STR
from picard.disc import discid_version
from picard.util.astrcmp import astrcmp_implementation

_versions = OrderedDict([
    ("version", PICARD_FANCY_VERSION_STR),
    ("pyqt-version", pyqt_version),
    ("qt-version", QT_VERSION_STR),
    ("mutagen-version", mutagen_version),
    ("discid-version", discid_version),
    ("astrcmp", astrcmp_implementation),
    ("SSL", QSslSocket.sslLibraryVersionString())
])

_names = {
    "version": "Picard",
    "pyqt-version": "PyQt",
    "qt-version": "Qt",
    "mutagen-version": "Mutagen",
    "discid-version": "Discid",
    "astrcmp": "astrcmp",
    "SSL": "SSL",
}


def _value_as_text(value, i18n=False):
    if not value:
示例#24
0
    def createRequest(self, op, request, outgoingData=None):
        """
        Public method to create a request.
        
        @param op the operation to be performed
            (QNetworkAccessManager.Operation)
        @param request reference to the request object (QNetworkRequest)
        @param outgoingData reference to an IODevice containing data to be sent
            (QIODevice)
        @return reference to the created reply object (QNetworkReply)
        """
        scheme = request.url().scheme()
        if scheme == "https" and \
                (not SSL_AVAILABLE or not QSslSocket.supportsSsl()):
            from .NetworkProtocolUnknownErrorReply import \
                NetworkProtocolUnknownErrorReply
            return NetworkProtocolUnknownErrorReply(scheme, self)

        import Helpviewer.HelpWindow

        if op == QNetworkAccessManager.PostOperation and \
                outgoingData is not None:
            outgoingDataByteArray = outgoingData.peek(1024 * 1024)
            Helpviewer.HelpWindow.HelpWindow.passwordManager().post(
                request, outgoingDataByteArray)

        reply = None
        if scheme in self.__schemeHandlers:
            reply = self.__schemeHandlers[scheme]\
                        .createRequest(op, request, outgoingData)
        if reply is not None:
            return reply

        # give GreaseMonkey the chance to create a request
        reply = Helpviewer.HelpWindow.HelpWindow.greaseMonkeyManager()\
            .createRequest(op, request, outgoingData)
        if reply is not None:
            return reply

        req = QNetworkRequest(request)
        if req.rawHeader(b"X-Eric6-UserLoadAction") == QByteArray(b"1"):
            req.setRawHeader(b"X-Eric6-UserLoadAction", QByteArray())
            req.setAttribute(QNetworkRequest.User + 200, "")
        else:
            req.setAttribute(QNetworkRequest.User + 200,
                             req.rawHeader(b"Referer"))

        if hasattr(QNetworkRequest, 'HttpPipeliningAllowedAttribute'):
            req.setAttribute(QNetworkRequest.HttpPipeliningAllowedAttribute,
                             True)
        if not self.__acceptLanguage.isEmpty():
            req.setRawHeader(b"Accept-Language", self.__acceptLanguage)

        # AdBlock code
        if op == QNetworkAccessManager.GetOperation:
            if self.__adblockNetwork is None:
                self.__adblockNetwork = \
                    Helpviewer.HelpWindow.HelpWindow.adBlockManager().network()
            reply = self.__adblockNetwork.block(req)
            if reply is not None:
                reply.setParent(self)
                return reply

        # set cache policy
        if op == QNetworkAccessManager.GetOperation:
            urlHost = req.url().host()
            for host in Preferences.getHelp("NoCacheHosts"):
                if host in urlHost:
                    req.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                                     QNetworkRequest.AlwaysNetwork)
                    break
            else:
                req.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                                 Preferences.getHelp("CachePolicy"))
        else:
            req.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
                             QNetworkRequest.AlwaysNetwork)

        # Do Not Track feature
        if self.__doNotTrack:
            req.setRawHeader(b"DNT", b"1")
            req.setRawHeader(b"X-Do-Not-Track", b"1")

        # Send referer header?
        if not self.__sendReferer and \
           req.url().host() not in Preferences.getHelp("SendRefererWhitelist"):
            req.setRawHeader(b"Referer", b"")

        reply = QNetworkAccessManager.createRequest(self, op, req,
                                                    outgoingData)
        self.requestCreated.emit(op, req, reply)

        return reply
示例#25
0
 def incomingConnection(self, handle):
     socket = QSslSocket()
     if socket.setSocketDescriptor(handle):
         if blockedAddresses.get(socket.peerAddress(), 1) <= 0:
             socket.close()
             return
         def handleSslErrors(errors, socket = socket):
             address = socket.peerAddress().toString()
             log('SSL errors for peer ' + address + ' : ' + ', '.join([x.errorString() for x in errors]))
         socket.sslErrors.connect(handleSslErrors)
         socket.setLocalCertificate(QSslCertificate(base64.b64decode(certificate)))
         socket.setPrivateKey(QSslKey(base64.b64decode(privatekey), QSsl.Rsa))
         socket.startServerEncryption()
         self.addPendingConnection(socket)
示例#26
0
 def __connectNetwork(self, name, connect, silent):
     """
     Private slot to connect to or disconnect from the given network.
     
     @param name name of the network to connect to (string)
     @param connect flag indicating to connect (boolean)
     @param silent flag indicating a silent connect/disconnect (boolean)
     """
     if connect:
         network = self.__ircNetworkManager.getNetwork(name)
         if network:
             self.__server = network.getServer()
             self.__identityName = network.getIdentityName()
             identity = self.__ircNetworkManager.getIdentity(
                 self.__identityName)
             if identity:
                 self.__userName = identity.getIdent()
                 self.__quitMessage = identity.getQuitMessage()
                 if self.__server:
                     useSSL = self.__server.useSSL()
                     if useSSL and not SSL_AVAILABLE:
                         E5MessageBox.critical(
                             self,
                             self.tr("SSL Connection"),
                             self.tr(
                                 """An encrypted connection to the IRC"""
                                 """ network was requested but SSL is not"""
                                 """ available. Please change the server"""
                                 """ configuration."""))
                         return
                     
                     if useSSL:
                         # create SSL socket
                         self.__socket = QSslSocket(self)
                         self.__socket.encrypted.connect(
                             self.__hostConnected)
                         self.__socket.sslErrors.connect(
                             self.__sslErrors)
                     else:
                         # create TCP socket
                         self.__socket = QTcpSocket(self)
                         self.__socket.connected.connect(
                             self.__hostConnected)
                     self.__socket.hostFound.connect(
                         self.__hostFound)
                     self.__socket.disconnected.connect(
                         self.__hostDisconnected)
                     self.__socket.readyRead.connect(
                         self.__readyRead)
                     self.__socket.error.connect(
                         self.__tcpError)
                     
                     self.__connectionState = IrcWidget.ServerConnecting
                     if useSSL:
                         self.networkWidget.addServerMessage(
                             self.tr("Info"),
                             self.tr("Looking for server {0} (port {1})"
                                     " using an SSL encrypted connection"
                                     "...").format(self.__server.getName(),
                                                   self.__server.getPort()))
                         self.__socket.connectToHostEncrypted(
                             self.__server.getName(),
                             self.__server.getPort()
                         )
                     else:
                         self.networkWidget.addServerMessage(
                             self.tr("Info"),
                             self.tr(
                                 "Looking for server {0} (port {1})...")
                             .format(
                                 self.__server.getName(),
                                 self.__server.getPort()))
                         self.__socket.connectToHost(
                             self.__server.getName(),
                             self.__server.getPort())
     else:
         if silent:
             ok = True
         else:
             ok = E5MessageBox.yesNo(
                 self,
                 self.tr("Disconnect from Server"),
                 self.tr("""<p>Do you really want to disconnect from"""
                         """ <b>{0}</b>?</p><p>All channels will be"""
                         """ closed.</p>""")
                 .format(self.__server.getName()))
         if ok:
             if self.__server is not None:
                 self.networkWidget.addServerMessage(
                     self.tr("Info"),
                     self.tr("Disconnecting from server {0}...").format(
                         self.__server.getName()))
             elif name:
                 self.networkWidget.addServerMessage(
                     self.tr("Info"),
                     self.tr("Disconnecting from network {0}...").format(
                         name))
             else:
                 self.networkWidget.addServerMessage(
                     self.tr("Info"),
                     self.tr("Disconnecting from server."))
             self.__closeAllChannels()
             self.__send("QUIT :" + self.__quitMessage)
             if self.__socket:
                 self.__socket.flush()
                 self.__socket.close()
                 if self.__socket:
                     # socket is still existing
                     self.__socket.deleteLater()
                     self.__socket = None
             self.__userName = ""
             self.__identityName = ""
             self.__quitMessage = ""
示例#27
0
class MyServer(QTcpServer):
    def __init__(self):
        super().__init__()
        self.timerDict = dict()
        self.lastLogMinute = datetime.now().minute // 10
        self.watchDogTimer = self.startTimer(30000)
        self.restartTimer = None
        self.testSocket = QSslSocket()
        self.testSocket.setCaCertificates([QSslCertificate(base64.b64decode(certificate))])
        def onTestSuccess():
            if self.restartTimer:
                self.killTimer(self.restartTimer)
                self.restartTimer = None
            minute = datetime.now().minute // 10
            if minute != self.lastLogMinute:
                log('server ok, tot: ' + str(Session.IdCounter) + ' open: ' + str(len(openSessions)) +
                    ' active: ' + str(len(activeSessions)) + ' unv: ' + str(len(unvalidatedSockets)) +
                    ' cached: ' + str(len(fileHashDict)) + ' join: ' + str(len(joiningClients)) +
                    ' blockd: ' + str(len(blockedAddresses)) + ' ctrl: ' + str(len(controlHandlers)))
                self.lastLogMinute = minute
            self.testSocket.disconnectFromHost()
        self.testSocket.encrypted.connect(onTestSuccess)
        self.newConnection.connect(self.handleNewConnection)

    def __del__(self):
        log('Server deleted - ' + traceback.format_exc())

    def restart(self):
        self.close()
        subprocess.Popen([sys.executable, os.path.normpath(sys.argv[0])], close_fds=True)
        app.exit(0)

    def timerEvent(self, event : QTimerEvent):
        id = event.timerId()
        if id == self.restartTimer:
            log('restarting server because test socket cannot connect')
            self.restart()
        elif id == self.watchDogTimer:
            if self.testSocket.state() == QSslSocket.UnconnectedState and not self.restartTimer:
                self.restartTimer = self.startTimer(30000)
                self.testSocket.connectToHostEncrypted('localhost', listenPort)
        else:
            self.killTimer(id)
            socket = self.timerDict[id]
            socket.close()
            socket.deleteLater()
            del self.timerDict[id]
            if socket in unvalidatedSockets:
                unvalidatedSockets.remove(socket)

    def incomingConnection(self, handle):
        socket = QSslSocket()
        if socket.setSocketDescriptor(handle):
            if blockedAddresses.get(socket.peerAddress(), 1) <= 0:
                socket.close()
                return
            def handleSslErrors(errors, socket = socket):
                address = socket.peerAddress().toString()
                log('SSL errors for peer ' + address + ' : ' + ', '.join([x.errorString() for x in errors]))
            socket.sslErrors.connect(handleSslErrors)
            socket.setLocalCertificate(QSslCertificate(base64.b64decode(certificate)))
            socket.setPrivateKey(QSslKey(base64.b64decode(privatekey), QSsl.Rsa))
            socket.startServerEncryption()
            self.addPendingConnection(socket)

    def handleNewConnection(self):
        while True:
            socket = self.nextPendingConnection()
            if not socket:
                return
            timerId = self.startTimer(30000)
            self.timerDict[timerId] = socket
            def handleNewEncryptedConnection(socket = socket, timerId = timerId):
                unvalidatedSockets.add(socket)
                def handleDisconnect(socket = socket):
                    unvalidatedSockets.remove(socket)
                socket.disconnected.connect(handleDisconnect)
                def handleReceive(socket = socket, timerId = timerId):
                    if timerId:
                        self.killTimer(timerId)
                    unvalidatedSockets.remove(socket)
                    socket.disconnected.disconnect(handleDisconnect)
                    def blockAddress():
                        address = socket.peerAddress()
                        remaining = blockedAddresses.setdefault(address, 3)
                        blockedAddresses[address] -= 1
                        if remaining == 1:  # was last trial
                            socket.write(b"your address '" + address.toString().encode() + b"' has been blocked\n")
                            log("block address '" + address.toString() + "'")
                        socket.disconnectFromHost()
                    try:
                        secretLen = int(socket.read(1))
                    except:
                        blockAddress()
                        return
                    secret = socket.read(secretLen)
                    if secret == b'ctrl4eip':
                        blockedAddresses.pop(socket.peerAddress(), None)
                        controlHandlers.add(ControlHandler(socket))
                        socket.readyRead.disconnect(handleReceive)
                    elif secret == sessionClientSecret:
                        blockedAddresses.pop(socket.peerAddress(), None)
                        clientSocket = ClientSocket(socket)
                        clientSocket.register(validatedSockets)
                        clientSocket.setReceiveHandler(handleValidatedReceive)
                        socket.readyRead.disconnect(handleReceive)
                        clientSocket.handleReceive()
                    else:
                        address = socket.peerAddress()
                        remaining = blockedAddresses.setdefault(address, 3)
                        blockedAddresses[address] -= 1
                        if remaining == 1: # was last trial
                            socket.write(b"your address '" + address.toString().encode() + b"' has been blocked\n")
                            log("block address '" + address.toString() + "'")
                        socket.disconnectFromHost()
                        return
                socket.readyRead.connect(handleReceive)

            if socket.isEncrypted():
                handleNewEncryptedConnection()
            else:
                socket.encrypted.connect(handleNewEncryptedConnection)
示例#28
0
 def createRequest(self, op, request, outgoingData=None):
     """
     Public method to create a request.
     
     @param op the operation to be performed
         (QNetworkAccessManager.Operation)
     @param request reference to the request object (QNetworkRequest)
     @param outgoingData reference to an IODevice containing data to be sent
         (QIODevice)
     @return reference to the created reply object (QNetworkReply)
     """
     scheme = request.url().scheme()
     if scheme == "https" and \
             (not SSL_AVAILABLE or not QSslSocket.supportsSsl()):
         from .NetworkProtocolUnknownErrorReply import \
             NetworkProtocolUnknownErrorReply
         return NetworkProtocolUnknownErrorReply(scheme, self)
     
     import Helpviewer.HelpWindow
     
     if op == QNetworkAccessManager.PostOperation and \
             outgoingData is not None:
         outgoingDataByteArray = outgoingData.peek(1024 * 1024)
         Helpviewer.HelpWindow.HelpWindow.passwordManager().post(
             request, outgoingDataByteArray)
     
     reply = None
     if scheme in self.__schemeHandlers:
         reply = self.__schemeHandlers[scheme]\
                     .createRequest(op, request, outgoingData)
     if reply is not None:
         return reply
     
     # give GreaseMonkey the chance to create a request
     reply = Helpviewer.HelpWindow.HelpWindow.greaseMonkeyManager()\
         .createRequest(op, request, outgoingData)
     if reply is not None:
         return reply
     
     req = QNetworkRequest(request)
     if req.rawHeader(b"X-Eric6-UserLoadAction") == QByteArray(b"1"):
         req.setRawHeader(b"X-Eric6-UserLoadAction", QByteArray())
         req.setAttribute(QNetworkRequest.User + 200, "")
     else:
         req.setAttribute(
             QNetworkRequest.User + 200, req.rawHeader(b"Referer"))
     
     if hasattr(QNetworkRequest, 'HttpPipeliningAllowedAttribute'):
         req.setAttribute(
             QNetworkRequest.HttpPipeliningAllowedAttribute, True)
     if not self.__acceptLanguage.isEmpty():
         req.setRawHeader(b"Accept-Language", self.__acceptLanguage)
     
     # AdBlock code
     if op == QNetworkAccessManager.GetOperation:
         if self.__adblockNetwork is None:
             self.__adblockNetwork = \
                 Helpviewer.HelpWindow.HelpWindow.adBlockManager().network()
         reply = self.__adblockNetwork.block(req)
         if reply is not None:
             reply.setParent(self)
             return reply
     
     # set cache policy
     if op == QNetworkAccessManager.GetOperation:
         urlHost = req.url().host()
         for host in Preferences.getHelp("NoCacheHosts"):
             if host in urlHost:
                 req.setAttribute(
                     QNetworkRequest.CacheLoadControlAttribute,
                     QNetworkRequest.AlwaysNetwork)
                 break
         else:
             req.setAttribute(
                 QNetworkRequest.CacheLoadControlAttribute,
                 Preferences.getHelp("CachePolicy"))
     else:
         req.setAttribute(
             QNetworkRequest.CacheLoadControlAttribute,
             QNetworkRequest.AlwaysNetwork)
     
     # Do Not Track feature
     if self.__doNotTrack:
         req.setRawHeader(b"DNT", b"1")
         req.setRawHeader(b"X-Do-Not-Track", b"1")
     
     # Send referer header?
     if not self.__sendReferer and \
        req.url().host() not in Preferences.getHelp("SendRefererWhitelist"):
         req.setRawHeader(b"Referer", b"")
     
     reply = QNetworkAccessManager.createRequest(
         self, op, req, outgoingData)
     self.requestCreated.emit(op, req, reply)
     
     return reply
示例#29
0
#     Copyright 2019, Kay Hayen, mailto:[email protected]
#
#     Python test originally created or extracted from other peoples work. The
#     parts from me are licensed as below. It is at least Free Software where
#     it's copied from other people. In these cases, that will normally be
#     indicated.
#
#     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.
#
from PyQt5.QtNetwork import QSslSocket
print("SSL support: %r" % (QSslSocket.supportsSsl(),))
def check_ssl():
    if not QSslSocket.supportsSsl():
        pytest.skip("QtNetwork SSL not supported")
def check_ssl():
    if not QSslSocket.supportsSsl():
        pytest.skip("QtNetwork SSL not supported")
示例#32
0
#     Copyright 2020, Kay Hayen, mailto:[email protected]
#
#     Python test originally created or extracted from other peoples work. The
#     parts from me are licensed as below. It is at least Free Software where
#     it's copied from other people. In these cases, that will normally be
#     indicated.
#
#     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.
#
from PyQt5.QtNetwork import QSslSocket

# nuitka-skip-unless-imports: PyQt5.QtGui

print("SSL support: %r" % (QSslSocket.supportsSsl(), ))
示例#33
0
def version_info() -> str:
    """Return a string with various version information."""
    lines = _LOGO.lstrip('\n').splitlines()

    lines.append("qutebrowser v{}".format(qutebrowser.__version__))
    gitver = _git_str()
    if gitver is not None:
        lines.append("Git commit: {}".format(gitver))

    lines.append('Backend: {}'.format(_backend()))
    lines.append('Qt: {}'.format(earlyinit.qt_version()))

    lines += [
        '',
        '{}: {}'.format(platform.python_implementation(),
                        platform.python_version()),
        'PyQt: {}'.format(PYQT_VERSION_STR),
        '',
    ]

    lines += _module_versions()

    lines += [
        'pdf.js: {}'.format(_pdfjs_version()),
        'sqlite: {}'.format(sql.version()),
        'QtNetwork SSL: {}\n'.format(QSslSocket.sslLibraryVersionString(
        ) if QSslSocket.supportsSsl() else 'no'),
    ]

    if objects.qapp:
        style = objects.qapp.style()
        lines.append('Style: {}'.format(style.metaObject().className()))
        lines.append('Platform plugin: {}'.format(objects.qapp.platformName()))
        lines.append('OpenGL: {}'.format(opengl_info()))

    importpath = os.path.dirname(os.path.abspath(qutebrowser.__file__))

    lines += [
        'Platform: {}, {}'.format(platform.platform(),
                                  platform.architecture()[0]),
    ]
    dist = distribution()
    if dist is not None:
        lines += [
            'Linux distribution: {} ({})'.format(dist.pretty, dist.parsed.name)
        ]

    lines += [
        'Frozen: {}'.format(hasattr(sys, 'frozen')),
        "Imported from {}".format(importpath),
        "Using Python from {}".format(sys.executable),
        "Qt library executable path: {}, data path: {}".format(
            QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath),
            QLibraryInfo.location(QLibraryInfo.DataPath))
    ]

    if not dist or dist.parsed == Distribution.unknown:
        lines += _os_info()

    lines += [
        '',
        'Paths:',
    ]
    for name, path in sorted(_path_info().items()):
        lines += ['{}: {}'.format(name, path)]

    lines += [
        '', 'Autoconfig loaded: {}'.format(_autoconfig_loaded()),
        'Config.py: {}'.format(_config_py_loaded()),
        'Uptime: {}'.format(_uptime())
    ]

    return '\n'.join(lines)
示例#34
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.
"""Our own QNetworkAccessManager."""

from PyQt5.QtCore import pyqtSlot, PYQT_VERSION, QCoreApplication
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply

try:
    from PyQt5.QtNetwork import QSslSocket
except ImportError:
    SSL_AVAILABLE = False
else:
    SSL_AVAILABLE = QSslSocket.supportsSsl()

from qutebrowser.config import config
from qutebrowser.utils import message, log, usertypes, utils, objreg
from qutebrowser.network import qutescheme, schemehandler


class NetworkManager(QNetworkAccessManager):
    """Our own QNetworkAccessManager.

    Attributes:
        _requests: Pending requests.
        _scheme_handlers: A dictionary (scheme -> handler) of supported custom
                          schemes.
        _win_id: The window ID this NetworkManager is associated with.
    """