#!/usr/bin/env python

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

import os
import random

from lib.core.common import singleTimeWarnMessage
from lib.core.compat import xrange
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.LOW

def dependencies():
    singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL))

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

    Requirement:
        * MySQL

    Tested against:
        * MySQL 5.1

    Notes:
        * Useful to bypass several web application firewalls

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

    # ASCII table:
    #   TAB     09      horizontal TAB
    #   LF      0A      new line
    #   FF      0C      new page
    #   CR      0D      carriage return
    #   VT      0B      vertical TAB        (MySQL and Microsoft SQL Server only)
    #           A0      non-breaking space
    # 定义一个包含特殊字符的元组
    blanks = ('%09', '%0A', '%0C', '%0D', '%0B', '%A0')
    # 将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
                    # 将一个随机选择的特殊字符添加到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
