| 1 |
# |
| 2 |
# General code for JSBeautifier unpackers infrastructure. See README.specs |
| 3 |
# written by Stefano Sanfilippo <[email protected]> |
| 4 |
# |
| 5 |
|
| 6 |
"""General code for JSBeautifier unpackers infrastructure.""" |
| 7 |
|
| 8 |
import pkgutil |
| 9 |
import re |
| 10 |
from jsbeautifier.unpackers import evalbased |
| 11 |
|
| 12 |
# NOTE: AT THE MOMENT, IT IS DEACTIVATED FOR YOUR SECURITY: it runs js! |
| 13 |
BLACKLIST = ["jsbeautifier.unpackers.evalbased"] |
| 14 |
|
| 15 |
|
| 16 |
class UnpackingError(Exception): |
| 17 |
"""Badly packed source or general error. Argument is a |
| 18 |
meaningful description.""" |
| 19 |
|
| 20 |
pass |
| 21 |
|
| 22 |
|
| 23 |
def getunpackers(): |
| 24 |
"""Scans the unpackers dir, finds unpackers and add them to UNPACKERS list. |
| 25 |
An unpacker will be loaded only if it is a valid python module (name must |
| 26 |
adhere to naming conventions) and it is not blacklisted (i.e. inserted |
| 27 |
into BLACKLIST.""" |
| 28 |
path = __path__ |
| 29 |
prefix = __name__ + "." |
| 30 |
unpackers = [] |
| 31 |
interface = ["unpack", "detect", "PRIORITY"] |
| 32 |
for _importer, modname, _ispkg in pkgutil.iter_modules(path, prefix): |
| 33 |
if "tests" not in modname and modname not in BLACKLIST: |
| 34 |
try: |
| 35 |
module = __import__(modname, fromlist=interface) |
| 36 |
except ImportError: |
| 37 |
raise UnpackingError("Bad unpacker: %s" % modname) |
| 38 |
else: |
| 39 |
unpackers.append(module) |
| 40 |
|
| 41 |
return sorted(unpackers, key=lambda mod: mod.PRIORITY) |
| 42 |
|
| 43 |
|
| 44 |
UNPACKERS = getunpackers() |
| 45 |
|
| 46 |
|
| 47 |
def run(source, evalcode=False): |
| 48 |
"""Runs the applicable unpackers and return unpacked source as a string.""" |
| 49 |
for unpacker in [mod for mod in UNPACKERS if mod.detect(source)]: |
| 50 |
source = unpacker.unpack(source) |
| 51 |
if evalcode and evalbased.detect(source): |
| 52 |
source = evalbased.unpack(source) |
| 53 |
return source |
| 54 |
|
| 55 |
|
| 56 |
def filtercomments(source): |
| 57 |
"""NOT USED: strips trailing comments and put them at the top.""" |
| 58 |
trailing_comments = [] |
| 59 |
comment = True |
| 60 |
|
| 61 |
while comment: |
| 62 |
if re.search(r"^\s*\/\*", source): |
| 63 |
comment = source[0, source.index("*/") + 2] |
| 64 |
elif re.search(r"^\s*\/\/", source): |
| 65 |
comment = re.search(r"^\s*\/\/", source).group(0) |
| 66 |
else: |
| 67 |
comment = None |
| 68 |
|
| 69 |
if comment: |
| 70 |
source = re.sub(r"^\s+", "", source[len(comment) :]) |
| 71 |
trailing_comments.append(comment) |
| 72 |
|
| 73 |
return "\n".join(trailing_comments) + source |