#!/usr/bin/env python

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

# 导入操作系统相关的功能模块
import os

# 从lib.core.common导入XML文件解析函数
from lib.core.common import parseXmlFile
# 从lib.core.data导入全局变量存储对象kb和路径配置对象paths
from lib.core.data import kb
from lib.core.data import paths
# 导入指纹识别处理器类
from lib.parse.handler import FingerprintHandler

def headersParser(headers):
    """
    此函数通过解析HTTP请求头来识别:
    1. 后端数据库管理系统
    2. 操作系统类型
    3. Web应用技术栈
    参数headers: HTTP请求头字典
    """

    # 如果全局变量中还没有初始化headerPaths
    if not kb.headerPaths:
        # 初始化一个字典,存储不同HTTP头对应的XML规则文件路径
        kb.headerPaths = {
            # SharePoint服务器特征识别规则
            "microsoftsharepointteamservices": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "sharepoint.xml"),
            # 服务器类型识别规则
            "server": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "server.xml"),
            # Java Servlet容器识别规则
            "servlet-engine": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "servlet-engine.xml"),
            # Cookie特征识别规则
            "set-cookie": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "set-cookie.xml"),
            # ASP.NET版本识别规则
            "x-aspnet-version": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-aspnet-version.xml"),
            # 服务端技术栈识别规则
            "x-powered-by": os.path.join(paths.SQLMAP_XML_BANNER_PATH, "x-powered-by.xml"),
        }

    # 遍历HTTP头,将头名称转为小写并检查是否在规则文件字典中
    for header in (_.lower() for _ in headers if _.lower() in kb.headerPaths):
        # 获取该HTTP头的值
        value = headers[header]
        # 获取对应的XML规则文件路径
        xmlfile = kb.headerPaths[header]
        # 创建一个指纹识别处理器实例
        handler = FingerprintHandler(value, kb.headersFp)
        # 解析特定规则文件
        parseXmlFile(xmlfile, handler)
        # 解析通用规则文件
        parseXmlFile(paths.GENERIC_XML, handler)
