ExtensionCrawler/grepper

179 lines
5.6 KiB
Plaintext
Raw Normal View History

2017-09-01 13:12:05 +00:00
#!/usr/bin/env python3.5
2017-07-05 19:55:41 +00:00
#
# Copyright (C) 2016,2017 The University of Sheffield, UK
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import getopt
import os
import sys
import tarfile
import traceback
2017-07-10 12:17:48 +00:00
import jsbeautifier
2017-08-23 15:52:18 +00:00
import fnmatch
from multiprocessing import Pool, Lock
2017-07-05 19:55:41 +00:00
from zipfile import ZipFile
2017-07-31 13:19:52 +00:00
from functools import partial
import re
from ExtensionCrawler.config import const_basedir
2017-09-27 13:05:16 +00:00
from extfind import iter_extension_paths, iter_extension_paths_from_file
2017-07-05 19:55:41 +00:00
def help():
2017-08-23 15:52:18 +00:00
print("grepper [OPTION] GREP [FILE]")
print(" GREP regex pattern")
print(" [FILE] path(s) to extension tar")
print(" -h print this help text")
print(" -b beautify JavaScript before matching")
print(" -a <DIR> archive directory")
2017-09-27 13:05:16 +00:00
print(" -g <GLOB> glob on the extenion id, don't use with -e")
2017-08-23 15:52:18 +00:00
print(" -e <EXTIDFILELIST> file with extension ids")
print(" -t <THREADS> number of threads to use")
print(" -n <TASKID> process chunk n where n in [1,N]")
print(" -N <MAXTASKID> ")
def guarded_stdout(string):
lock.acquire()
sys.stdout.write(string)
lock.release()
def guarded_stderr(string):
lock.acquire()
sys.stderr.write(string)
lock.release()
2017-09-27 13:05:16 +00:00
def has_at_least_one_match(content, pattern):
for line in content.splitlines():
if re.search(pattern, line):
return True
return False
2017-08-23 15:52:18 +00:00
def process_crx(ext_id, date, crx, pattern, beautify):
try:
with ZipFile(crx) as z:
for zip_file_info in z.infolist():
if not zip_file_info.filename.endswith(".js"):
continue
with z.open(zip_file_info) as f:
content = f.read().decode(errors="surrogateescape")
if beautify:
2017-09-27 13:05:16 +00:00
if has_at_least_one_match(content, pattern):
content = jsbeautifier.beautify(content)
2017-08-23 15:52:18 +00:00
for i, line in enumerate(content.splitlines()):
if not re.search(pattern, line):
2017-08-14 13:40:10 +00:00
continue
2017-07-31 13:19:52 +00:00
args = [
2017-08-23 15:52:18 +00:00
ext_id, date, zip_file_info.filename + " (line " +
str(i + 1) + ")", line
2017-07-31 13:19:52 +00:00
]
2017-08-23 15:52:18 +00:00
guarded_stdout("|".join(args) + "\n")
2017-07-31 13:19:52 +00:00
2017-08-23 15:52:18 +00:00
except Exception:
guarded_stderr("Exception when handling {}, {}:\n{}".format(
ext_id, date, traceback.format_exc()))
2017-07-31 13:19:52 +00:00
2017-07-05 19:55:41 +00:00
2017-08-23 15:52:18 +00:00
def process_id(pattern, beautify, path):
try:
with tarfile.open(path, 'r') as t:
2017-08-14 13:40:10 +00:00
for tar_info in t.getmembers():
if not tar_info.name.endswith(".crx") or tar_info.size is 0:
continue
2017-08-23 15:52:18 +00:00
extid, date = tar_info.name.split("/")[:2]
with t.extractfile(tar_info) as crx:
process_crx(extid, date, crx, pattern, beautify)
except Exception:
guarded_stderr("Exception when handling {}:\n{}".format(
path, traceback.format_exc()))
2017-07-05 19:55:41 +00:00
2017-08-23 15:52:18 +00:00
def init(l):
global lock
lock = l
def parse_args(argv):
archive = const_basedir()
2017-08-14 13:40:10 +00:00
beautify = False
2017-07-05 19:55:41 +00:00
parallel = 8
2017-09-27 13:05:16 +00:00
extidglob = None
extidlistfile = None
2017-08-23 15:52:18 +00:00
taskid = 1
maxtaskid = 1
paths = []
2017-09-27 13:05:16 +00:00
2017-07-05 19:55:41 +00:00
try:
2017-08-23 15:52:18 +00:00
opts, args = getopt.getopt(argv, "ha:p:e:bt:n:N:", [
2017-09-27 13:05:16 +00:00
"archive=", "glob=", "extidlistfile=", "beautify", "threads=",
2017-08-23 15:52:18 +00:00
"taskid=", "maxtaskid="
])
2017-07-05 19:55:41 +00:00
except getopt.GetoptError:
help()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
help()
sys.exit()
elif opt in ("-a", "--archive"):
archive = arg
2017-09-27 13:05:16 +00:00
elif opt in ("-g", "--glob"):
extidglob = arg
2017-08-23 15:52:18 +00:00
elif opt in ("-e", "--extidlistfile"):
extidlistfile = arg
2017-08-14 13:40:10 +00:00
elif opt in ("-b", "--beautify"):
beautify = True
2017-07-05 19:55:41 +00:00
elif opt in ("-t", "--threads"):
parallel = int(arg)
2017-08-23 15:52:18 +00:00
elif opt in ("-n", "--taskid"):
taskid = int(arg)
elif opt in ("-N", "--maxtaskid"):
maxtaskid = int(arg)
2017-07-05 19:55:41 +00:00
2017-08-23 15:52:18 +00:00
if len(args) is 0:
2017-07-05 19:55:41 +00:00
help()
sys.exit(2)
2017-08-23 15:52:18 +00:00
pattern = args[0]
2017-09-27 13:05:16 +00:00
if len(args) > 1:
paths = args[1:]
elif extidglob is None and extidlistfile is None:
paths = iter_extension_paths(archive, taskid, maxtaskid)
elif extidglob is None and extidlistfile is not None:
paths = iter_extension_paths_from_file(archive, taskid, maxtaskid,
extidlistfile)
elif extidglob is not None and extidlistfile is None:
paths = iter_extension_paths(archive, taskid, maxtaskid, extidglob)
2017-08-23 15:52:18 +00:00
else:
2017-09-27 13:05:16 +00:00
help()
sys.exit(2)
2017-08-14 13:40:10 +00:00
2017-08-23 15:52:18 +00:00
return pattern, paths, beautify, parallel
2017-08-14 13:40:10 +00:00
2017-07-05 19:55:41 +00:00
2017-08-23 15:52:18 +00:00
def main(argv):
pattern, paths, beautify, parallel = parse_args(argv)
l = Lock()
with Pool(initializer=init, initargs=(l, ), processes=parallel) as p:
p.map(partial(process_id, pattern, beautify), paths)
2017-08-14 13:40:10 +00:00
2017-07-05 19:55:41 +00:00
if __name__ == "__main__":
main(sys.argv[1:])