#!/usr/bin/env python

"""
Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""

# 导入所需的模块
from lib.core.data import conf  # 导入配置信息
from lib.core.common import getSafeExString  # 导入安全字符串处理函数
from lib.core.exception import SqlmapConnectionException  # 导入SQL注入连接异常类
from thirdparty.six.moves import http_client as _http_client  # 导入HTTP客户端
from thirdparty.six.moves import urllib as _urllib  # 导入URL处理库

class HTTPSPKIAuthHandler(_urllib.request.HTTPSHandler):
    """
    HTTPS PKI认证处理器类
    继承自urllib的HTTPSHandler类,用于处理带客户端证书的HTTPS请求
    """
    def __init__(self, auth_file):
        """
        初始化函数
        参数:
            auth_file: 认证文件路径,包含客户端证书和私钥
        """
        _urllib.request.HTTPSHandler.__init__(self)  # 调用父类初始化
        self.auth_file = auth_file  # 保存认证文件路径

    def https_open(self, req):
        """
        处理HTTPS请求的方法
        参数:
            req: HTTPS请求对象
        返回:
            处理后的HTTPS连接
        """
        return self.do_open(self.getConnection, req)

    def getConnection(self, host, timeout=None):
        """
        建立HTTPS连接的方法
        参数:
            host: 目标主机
            timeout: 超时时间,默认为None
        返回:
            HTTPS连接对象
        异常:
            SqlmapConnectionException: 连接异常
        """
        try:
            # 创建带客户端证书的HTTPS连接
            # 参考文档: https://docs.python.org/2/library/ssl.html#ssl.SSLContext.load_cert_chain
            return _http_client.HTTPSConnection(host, 
                                              cert_file=self.auth_file,  # 证书文件
                                              key_file=self.auth_file,   # 私钥文件
                                              timeout=conf.timeout)      # 超时设置
        except IOError as ex:
            # 如果出现IO错误(比如证书文件无法读取等)
            errMsg = "error occurred while using key "
            errMsg += "file '%s' ('%s')" % (self.auth_file, getSafeExString(ex))
            raise SqlmapConnectionException(errMsg)  # 抛出SQL注入连接异常
