sqlmap/lib/core/decorators.py

96 lines
2.3 KiB
Python
Raw Normal View History

2019-05-08 13:47:52 +03:00
#!/usr/bin/env python
"""
2020-01-01 15:25:15 +03:00
Copyright (c) 2006-2020 sqlmap developers (http://sqlmap.org/)
2017-10-11 15:50:46 +03:00
See the file 'LICENSE' for copying permission
"""
import functools
2017-12-25 01:54:43 +03:00
import hashlib
2019-01-30 01:44:58 +03:00
import threading
2017-12-25 01:54:43 +03:00
2019-06-04 15:44:06 +03:00
from lib.core.datatype import LRUDict
2019-01-30 01:44:58 +03:00
from lib.core.settings import MAX_CACHE_ITEMS
2019-04-30 14:20:31 +03:00
from lib.core.settings import UNICODE_ENCODING
from lib.core.threads import getCurrentThreadData
2019-07-30 21:28:56 +03:00
_cache = {}
_cache_lock = threading.Lock()
_method_locks = {}
2019-01-30 01:44:58 +03:00
2019-07-30 21:28:56 +03:00
def cachedmethod(f):
"""
Method with a cached content
2019-05-06 15:41:35 +03:00
>>> __ = cachedmethod(lambda _: _)
>>> __(1)
1
>>> __ = cachedmethod(lambda *args, **kwargs: args[0])
>>> __(2)
2
>>> __ = cachedmethod(lambda *args, **kwargs: list(kwargs.values())[0])
>>> __(foobar=3)
3
Reference: http://code.activestate.com/recipes/325205-cache-decorator-in-python-24/
"""
2013-01-30 13:38:11 +04:00
2019-07-30 21:28:56 +03:00
_cache[f] = LRUDict(capacity=MAX_CACHE_ITEMS)
@functools.wraps(f)
2019-07-30 21:28:56 +03:00
def _f(*args, **kwargs):
2019-04-30 14:20:31 +03:00
key = int(hashlib.md5("|".join(str(_) for _ in (f, args, kwargs)).encode(UNICODE_ENCODING)).hexdigest(), 16) & 0x7fffffffffffffff
2016-05-14 15:18:34 +03:00
2019-02-10 01:18:08 +03:00
try:
with _cache_lock:
2019-07-30 21:28:56 +03:00
result = _cache[f][key]
2019-02-10 01:18:08 +03:00
except KeyError:
result = f(*args, **kwargs)
with _cache_lock:
2019-07-30 21:28:56 +03:00
_cache[f][key] = result
2019-02-10 01:18:08 +03:00
return result
2013-01-30 13:38:11 +04:00
2019-07-30 21:28:56 +03:00
return _f
def stackedmethod(f):
"""
Method using pushValue/popValue functions (fallback function for stack realignment)
2019-05-06 15:41:35 +03:00
>>> threadData = getCurrentThreadData()
>>> original = len(threadData.valueStack)
>>> __ = stackedmethod(lambda _: threadData.valueStack.append(_))
>>> __(1)
>>> len(threadData.valueStack) == original
True
"""
@functools.wraps(f)
def _(*args, **kwargs):
threadData = getCurrentThreadData()
originalLevel = len(threadData.valueStack)
try:
result = f(*args, **kwargs)
finally:
if len(threadData.valueStack) > originalLevel:
threadData.valueStack = threadData.valueStack[:originalLevel]
return result
2018-06-10 00:38:00 +03:00
return _
def lockedmethod(f):
@functools.wraps(f)
def _(*args, **kwargs):
if f not in _method_locks:
2019-08-11 02:32:20 +03:00
_method_locks[f] = threading.RLock()
with _method_locks[f]:
result = f(*args, **kwargs)
return result
return _