#!/usr/bin/env python

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

import random

from lib.core.compat import xrange
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.LOW

def dependencies():
    pass

def tamper(payload, **kwargs):
    """
    Replaces space character (' ') with a random blank character from a valid set of alternate characters

    Tested against:
        * Microsoft SQL Server 2005
        * MySQL 4, 5.0 and 5.5
        * Oracle 10g
        * PostgreSQL 8.3, 8.4, 9.0

    Notes:
        * Useful to bypass several web application firewalls

    >>> random.seed(0)
    >>> tamper('SELECT id FROM users')
    'SELECT%0Did%0CFROM%0Ausers'
    """

    # ASCII table:
    #   TAB     09      horizontal TAB
    #   LF      0A      new line
    #   FF      0C      new page
    #   CR      0D      carriage return
    # 定义一个包含特殊字符的列表
    blanks = ("%09", "%0A", "%0C", "%0D")
    # 将payload赋值给retVal
    retVal = payload

    # 如果payload不为空
    if payload:
        # 将retVal置为空字符串
        retVal = ""
        # 定义三个布尔变量，分别表示是否在引号内、双引号内和第一个空格
        quote, doublequote, firstspace = False, False, False

        # 遍历payload的每个字符
        for i in xrange(len(payload)):
            # 如果第一个字符不是空格
            if not firstspace:
                # 如果当前字符是空格
                if payload[i].isspace():
                    # 将firstspace置为True
                    firstspace = True
                    # 在retVal中添加一个随机选择的特殊字符
                    retVal += random.choice(blanks)
                    # 继续下一次循环
                    continue

            # 如果当前字符是单引号
            elif payload[i] == '\'':
                # 将quote取反
                quote = not quote

            # 如果当前字符是双引号
            elif payload[i] == '"':
                # 将doublequote取反
                doublequote = not doublequote

            # 如果当前字符是空格，且不在双引号和单引号内
            elif payload[i] == ' ' and not doublequote and not quote:
                # 在retVal中添加一个随机选择的特殊字符
                retVal += random.choice(blanks)
                # 继续下一次循环
                continue

            # 将当前字符添加到retVal中
            retVal += payload[i]

    # 返回retVal
    return retVal
