open-pushscan 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- open_pushscan/__init__.py +2 -0
- open_pushscan/__main__.py +5 -0
- open_pushscan/agents.py +666 -0
- open_pushscan/ci.py +88 -0
- open_pushscan/cli.py +534 -0
- open_pushscan/config.py +256 -0
- open_pushscan/fingerprints.py +153 -0
- open_pushscan/gitscan.py +248 -0
- open_pushscan/hooks.py +121 -0
- open_pushscan/i18n.py +90 -0
- open_pushscan/media.py +318 -0
- open_pushscan/publish.py +160 -0
- open_pushscan/report.py +130 -0
- open_pushscan/rules.py +277 -0
- open_pushscan/scanner.py +226 -0
- open_pushscan/visibility.py +87 -0
- open_pushscan-0.3.0.dist-info/METADATA +193 -0
- open_pushscan-0.3.0.dist-info/RECORD +22 -0
- open_pushscan-0.3.0.dist-info/WHEEL +5 -0
- open_pushscan-0.3.0.dist-info/entry_points.txt +2 -0
- open_pushscan-0.3.0.dist-info/licenses/LICENSE +202 -0
- open_pushscan-0.3.0.dist-info/top_level.txt +1 -0
open_pushscan/hooks.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Install once per computer. git's global core.hooksPath points at our folder, so every repository
|
|
2
|
+
(including ones cloned later) is checked. Each repository's own hooks (for example git-lfs) still run after ours.
|
|
3
|
+
"""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import stat
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import config
|
|
12
|
+
|
|
13
|
+
CHECKED = ('pre-commit', 'commit-msg', 'pre-push')
|
|
14
|
+
# Hooks we do not check, but must keep running for tools such as git-lfs, husky or pre-commit.
|
|
15
|
+
PASS_THROUGH = ('applypatch-msg', 'pre-applypatch', 'post-applypatch', 'prepare-commit-msg', 'post-commit', 'pre-rebase',
|
|
16
|
+
'post-checkout', 'post-merge', 'pre-merge-commit', 'post-rewrite', 'pre-auto-gc', 'reference-transaction',
|
|
17
|
+
'push-to-checkout', 'sendemail-validate', 'post-index-change')
|
|
18
|
+
MARK = '# open-pushscan'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def hooks_dir() -> str:
|
|
22
|
+
return config.path('hooks')
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _python() -> str:
|
|
26
|
+
return sys.executable.replace('\\', '/')
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _script(name: str) -> str:
|
|
30
|
+
py = _python()
|
|
31
|
+
stdin = name in ('pre-push', 'reference-transaction', 'post-rewrite', 'pre-receive')
|
|
32
|
+
chain = f'''own="$(git rev-parse --git-dir)/hooks/{name}"
|
|
33
|
+
if [ -f "$own" ] && ! grep -q -e git-public-check -e open-pushscan "$own" 2>/dev/null; then
|
|
34
|
+
{'printf "%s" "$input" | ' if stdin else ''}"$own" "$@" || exit $?
|
|
35
|
+
fi
|
|
36
|
+
prev="$(git config --global open-pushscan.previousHooksPath)"
|
|
37
|
+
if [ -n "$prev" ] && [ -f "$prev/{name}" ]; then
|
|
38
|
+
{'printf "%s" "$input" | ' if stdin else ''}"$prev/{name}" "$@" || exit $?
|
|
39
|
+
fi
|
|
40
|
+
exit 0
|
|
41
|
+
'''
|
|
42
|
+
lines = ['#!/bin/sh', f'{MARK}: made by `open-pushscan setup`; run it again to rebuild this file.']
|
|
43
|
+
if stdin:
|
|
44
|
+
lines.append('input="$(cat; echo x)"; input="${input%x}"')
|
|
45
|
+
if name in CHECKED:
|
|
46
|
+
call = f'"{py}" -m open_pushscan hook {name} "$@"'
|
|
47
|
+
lines.append(f'printf "%s" "$input" | {call} || exit 1' if stdin else f'{call} || exit 1')
|
|
48
|
+
return '\n'.join(lines) + '\n' + chain
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def global_hooks_path() -> str:
|
|
52
|
+
p = subprocess.run(['git', 'config', '--global', '--get', 'core.hooksPath'], capture_output=True)
|
|
53
|
+
return p.stdout.decode().strip()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def installed() -> bool:
|
|
57
|
+
return os.path.normcase(os.path.abspath(os.path.expanduser(global_hooks_path() or '-'))) == os.path.normcase(os.path.abspath(hooks_dir()))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def install() -> str:
|
|
61
|
+
"""Write the hook scripts and point git at them. Returns the previous global hooksPath, if any."""
|
|
62
|
+
d = hooks_dir()
|
|
63
|
+
os.makedirs(d, exist_ok=True)
|
|
64
|
+
for name in CHECKED + PASS_THROUGH:
|
|
65
|
+
p = os.path.join(d, name)
|
|
66
|
+
with open(p, 'w', encoding='utf-8', newline='\n') as f:
|
|
67
|
+
f.write(_script(name))
|
|
68
|
+
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
69
|
+
prev = global_hooks_path()
|
|
70
|
+
was_ours = installed()
|
|
71
|
+
if prev and not was_ours:
|
|
72
|
+
subprocess.run(['git', 'config', '--global', 'open-pushscan.previousHooksPath', prev], check=False)
|
|
73
|
+
subprocess.run(['git', 'config', '--global', 'core.hooksPath', d.replace('\\', '/')], check=True)
|
|
74
|
+
return prev if prev and not was_ours else ''
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def uninstall() -> None:
|
|
78
|
+
prev = subprocess.run(['git', 'config', '--global', '--get', 'open-pushscan.previousHooksPath'], capture_output=True).stdout.decode().strip()
|
|
79
|
+
if installed():
|
|
80
|
+
if prev:
|
|
81
|
+
subprocess.run(['git', 'config', '--global', 'core.hooksPath', prev], check=False)
|
|
82
|
+
else:
|
|
83
|
+
subprocess.run(['git', 'config', '--global', '--unset', 'core.hooksPath'], check=False)
|
|
84
|
+
subprocess.run(['git', 'config', '--global', '--unset', 'open-pushscan.previousHooksPath'], check=False, capture_output=True)
|
|
85
|
+
d = hooks_dir()
|
|
86
|
+
if os.path.isdir(d):
|
|
87
|
+
for name in os.listdir(d):
|
|
88
|
+
try:
|
|
89
|
+
os.remove(os.path.join(d, name))
|
|
90
|
+
except OSError:
|
|
91
|
+
pass
|
|
92
|
+
try:
|
|
93
|
+
os.rmdir(d)
|
|
94
|
+
except OSError:
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def repo_override(cwd: str = '.') -> str:
|
|
99
|
+
"""A repository can set its own core.hooksPath, which hides ours. Returns it, or ''."""
|
|
100
|
+
p = subprocess.run(['git', 'config', '--local', '--get', 'core.hooksPath'], capture_output=True, cwd=cwd)
|
|
101
|
+
return p.stdout.decode().strip()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def find_overrides(root: str, max_depth: int = 6, limit: int = 2000) -> list:
|
|
105
|
+
"""Repositories under root that set their own hooksPath (so our checks do not run there)."""
|
|
106
|
+
found, seen = [], 0
|
|
107
|
+
skip = {'node_modules', '.cache', '.venv', 'venv', '__pycache__', '.git', 'site-packages', '.local', 'snap', '.npm', '.cargo'}
|
|
108
|
+
root_depth = root.rstrip(os.sep).count(os.sep)
|
|
109
|
+
for cur, dirs, _files in os.walk(root):
|
|
110
|
+
seen += 1
|
|
111
|
+
if seen > limit:
|
|
112
|
+
break
|
|
113
|
+
if os.path.isdir(os.path.join(cur, '.git')):
|
|
114
|
+
hp = repo_override(cur)
|
|
115
|
+
if hp:
|
|
116
|
+
found.append((cur, hp))
|
|
117
|
+
if cur.count(os.sep) - root_depth >= max_depth:
|
|
118
|
+
dirs[:] = []
|
|
119
|
+
else:
|
|
120
|
+
dirs[:] = [d for d in dirs if d not in skip and not d.startswith('.')]
|
|
121
|
+
return found
|
open_pushscan/i18n.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Messages in Traditional Chinese and English. The language follows the system unless set in config.ini."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import locale
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
|
|
8
|
+
from . import config
|
|
9
|
+
|
|
10
|
+
MESSAGES = {
|
|
11
|
+
# report headers
|
|
12
|
+
'blocked_push': ('open-pushscan 擋下了這次推送(目的地是公開的 repo)', 'open-pushscan stopped this push (it goes to a public repo)'),
|
|
13
|
+
'blocked_push_unknown': ('open-pushscan 擋下了這次推送(查不到目的地是公開還是私人,先當作公開)',
|
|
14
|
+
'open-pushscan stopped this push (could not tell whether the repo is public, so it is treated as public)'),
|
|
15
|
+
'blocked_commit': ('open-pushscan 擋下了這次 commit(這個 repo 會推到公開的地方)', 'open-pushscan stopped this commit (this repo is pushed somewhere public)'),
|
|
16
|
+
'blocked_commit_unknown': ('open-pushscan 擋下了這次 commit(查不到這個 repo 是公開還是私人,先當作公開)',
|
|
17
|
+
'open-pushscan stopped this commit (could not tell whether this repo is public, so it is treated as public)'),
|
|
18
|
+
'warn': ('open-pushscan 提醒:有 {n} 項可能不該公開(這是私人 repo,所以沒有擋)',
|
|
19
|
+
'open-pushscan: {n} thing(s) may not belong in public (this repo is private, so nothing was stopped)'),
|
|
20
|
+
'check_found': ('open-pushscan 找到 {n} 項可能不該公開的東西', 'open-pushscan found {n} thing(s) that may not belong in public'),
|
|
21
|
+
'check_clean': ('open-pushscan 檢查完了,沒有發現問題(看了 {what})', 'open-pushscan found nothing (checked {what})'),
|
|
22
|
+
'ci_nothing': ('open-pushscan:沒有新的 commit 要檢查(這次推送的 commit 之前已經檢查過)',
|
|
23
|
+
'open-pushscan: no new commits to check (the commits pushed had already been checked)'),
|
|
24
|
+
'ci_found': ('open-pushscan 找到 {n} 項不該公開的東西', 'open-pushscan found {n} thing(s) that should not be public'),
|
|
25
|
+
# labels
|
|
26
|
+
'why': ('為什麼', 'Why'),
|
|
27
|
+
'fix': ('怎麼改', 'Fix'),
|
|
28
|
+
'line': ('{path} 第 {line} 行', '{path} line {line}'),
|
|
29
|
+
'filename': ('檔名 {path}', 'file name {path}'),
|
|
30
|
+
'file': ('{path}', '{path}'),
|
|
31
|
+
'metadata': ('{path} 裡藏的資訊', 'hidden details of {path}'),
|
|
32
|
+
'message': ('commit 訊息', 'commit message'),
|
|
33
|
+
'author': ('commit 作者', 'commit author'),
|
|
34
|
+
'committer': ('commit 提交者', 'commit committer'),
|
|
35
|
+
'tag': ('標籤名稱', 'tag name'),
|
|
36
|
+
'in_commit': ('(commit {sha})', ' (commit {sha})'),
|
|
37
|
+
'same_as': ('(原因和改法同第 {n} 項)', '(same reason and fix as item {n})'),
|
|
38
|
+
'also': ('另外還出現在 {n} 個地方', 'also in {n} other place(s)'),
|
|
39
|
+
'more': ('還有 {n} 項沒列出來,用 {cmd} check --history 看全部', '{n} more not shown; run {cmd} check --history to see all'),
|
|
40
|
+
'contains': ('裡面有{what}', 'contains {what}'),
|
|
41
|
+
# footers
|
|
42
|
+
'foot_push': ('改好後重新 commit 再推。', 'Fix these, commit again, then push.'),
|
|
43
|
+
'foot_commit': ('改好後再 commit 一次。', 'Fix these, then commit again.'),
|
|
44
|
+
'foot_allow': ('確定第 {n} 項沒問題:{cmd} allow {n}', 'If item {n} is fine: {cmd} allow {n}'),
|
|
45
|
+
'foot_allow_any': ('確定某一項沒問題:{cmd} allow 編號', 'If an item is fine: {cmd} allow <number>'),
|
|
46
|
+
'notes': ('open-pushscan 提醒:有 {n} 行用「open-pushscan: allow」略過了檢查,請確認是你自己加的:',
|
|
47
|
+
'open-pushscan: {n} line(s) skip the checks with "open-pushscan: allow"; make sure you added them yourself:'),
|
|
48
|
+
# what was checked
|
|
49
|
+
'what_working': ('還沒 commit 的修改', 'uncommitted changes'),
|
|
50
|
+
'what_unpushed': ('{n} 個還沒推的 commit', '{n} unpushed commit(s)'),
|
|
51
|
+
'what_history': ('整段歷史,{n} 個 commit', 'the whole history, {n} commit(s)'),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def lang() -> str:
|
|
56
|
+
choice = (os.environ.get('OPEN_PUSHSCAN_LANG') or config.get('language') or 'auto').lower()
|
|
57
|
+
if choice.startswith('zh'):
|
|
58
|
+
return 'zh'
|
|
59
|
+
if choice.startswith('en'):
|
|
60
|
+
return 'en'
|
|
61
|
+
for var in ('LC_ALL', 'LC_MESSAGES', 'LANG', 'LANGUAGE'):
|
|
62
|
+
v = os.environ.get(var, '')
|
|
63
|
+
if v:
|
|
64
|
+
return 'zh' if v.lower().startswith('zh') else 'en'
|
|
65
|
+
if os.name == 'nt':
|
|
66
|
+
try:
|
|
67
|
+
import ctypes
|
|
68
|
+
return 'zh' if ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF == 0x04 else 'en'
|
|
69
|
+
except Exception:
|
|
70
|
+
pass
|
|
71
|
+
try:
|
|
72
|
+
loc = locale.getlocale()[0] or ''
|
|
73
|
+
except ValueError:
|
|
74
|
+
loc = ''
|
|
75
|
+
return 'zh' if loc.lower().startswith(('zh', 'chinese')) else 'en'
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def command() -> str:
|
|
79
|
+
"""What to type: the short command when it is on PATH, otherwise `python -m open_pushscan`
|
|
80
|
+
(a Windows `pip install --user` puts the short command in a folder that is not on PATH)."""
|
|
81
|
+
if shutil.which('open-pushscan'):
|
|
82
|
+
return 'open-pushscan'
|
|
83
|
+
return ('python' if os.name == 'nt' else 'python3') + ' -m open_pushscan'
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def t(key: str, l: str = None, **kw) -> str:
|
|
87
|
+
l = l or lang()
|
|
88
|
+
zh, en = MESSAGES[key]
|
|
89
|
+
kw.setdefault('cmd', command())
|
|
90
|
+
return (zh if l == 'zh' else en).format(**kw)
|
open_pushscan/media.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Details hidden inside images and documents: photo EXIF (GPS, owner, device), text inside PNG files,
|
|
2
|
+
and author fields of PDF and Office files. Only the Python standard library is used.
|
|
3
|
+
|
|
4
|
+
inspect(name, data) returns (findings, texts): findings are (rule id, what was found); texts are metadata
|
|
5
|
+
strings that the ordinary text rules (paths, host names, emails…) also look at.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import re
|
|
11
|
+
import struct
|
|
12
|
+
import zipfile
|
|
13
|
+
import zlib
|
|
14
|
+
|
|
15
|
+
# ---------------------------------------------------------------- EXIF (TIFF structure)
|
|
16
|
+
|
|
17
|
+
TAG_NAMES = {
|
|
18
|
+
0x010F: 'Make', 0x0110: 'Model', 0x013B: 'Artist', 0x8298: 'Copyright', 0x013C: 'HostComputer',
|
|
19
|
+
0x9C9D: 'XPAuthor', 0xA430: 'CameraOwnerName', 0xA431: 'BodySerialNumber', 0xA435: 'LensSerialNumber',
|
|
20
|
+
}
|
|
21
|
+
OWNER_TAGS = {'Artist', 'Copyright', 'HostComputer', 'XPAuthor', 'CameraOwnerName', 'BodySerialNumber', 'LensSerialNumber'}
|
|
22
|
+
TYPE_SIZE = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _tiff(data: bytes) -> dict:
|
|
26
|
+
"""Read the fields we care about from TIFF-structured EXIF data."""
|
|
27
|
+
out = {}
|
|
28
|
+
if len(data) < 8 or data[:2] not in (b'II', b'MM'):
|
|
29
|
+
return out
|
|
30
|
+
end = '<' if data[:2] == b'II' else '>'
|
|
31
|
+
|
|
32
|
+
def u16(o):
|
|
33
|
+
return struct.unpack_from(end + 'H', data, o)[0]
|
|
34
|
+
|
|
35
|
+
def u32(o):
|
|
36
|
+
return struct.unpack_from(end + 'I', data, o)[0]
|
|
37
|
+
|
|
38
|
+
def value(typ, count, voff):
|
|
39
|
+
size = TYPE_SIZE.get(typ, 1) * count
|
|
40
|
+
if size > 4:
|
|
41
|
+
off = u32(voff)
|
|
42
|
+
raw = data[off:off + size]
|
|
43
|
+
else:
|
|
44
|
+
raw = data[voff:voff + size]
|
|
45
|
+
if typ == 2:
|
|
46
|
+
return raw.split(b'\0')[0].decode('utf-8', 'replace').strip()
|
|
47
|
+
if typ in (1, 7):
|
|
48
|
+
return raw
|
|
49
|
+
if typ == 5:
|
|
50
|
+
return [struct.unpack_from(end + 'II', raw, i * 8) for i in range(count) if (i + 1) * 8 <= len(raw)]
|
|
51
|
+
if typ == 3:
|
|
52
|
+
return [struct.unpack_from(end + 'H', raw, i * 2)[0] for i in range(count) if (i + 1) * 2 <= len(raw)]
|
|
53
|
+
if typ == 4:
|
|
54
|
+
return [struct.unpack_from(end + 'I', raw, i * 4)[0] for i in range(count) if (i + 1) * 4 <= len(raw)]
|
|
55
|
+
return raw
|
|
56
|
+
|
|
57
|
+
def ifd(offset, kind, depth=0):
|
|
58
|
+
if depth > 4 or offset <= 0 or offset + 2 > len(data):
|
|
59
|
+
return
|
|
60
|
+
n = u16(offset)
|
|
61
|
+
for i in range(min(n, 512)):
|
|
62
|
+
e = offset + 2 + i * 12
|
|
63
|
+
if e + 12 > len(data):
|
|
64
|
+
return
|
|
65
|
+
tag, typ, count = u16(e), u16(e + 2), u32(e + 4)
|
|
66
|
+
try:
|
|
67
|
+
if kind == 'gps':
|
|
68
|
+
if tag in (1, 3):
|
|
69
|
+
out['gps_' + ('lat_ref' if tag == 1 else 'lon_ref')] = value(typ, count, e + 8)
|
|
70
|
+
elif tag in (2, 4):
|
|
71
|
+
out['gps_' + ('lat' if tag == 2 else 'lon')] = value(typ, count, e + 8)
|
|
72
|
+
continue
|
|
73
|
+
if tag == 0x8769:
|
|
74
|
+
ifd(u32(e + 8), 'exif', depth + 1)
|
|
75
|
+
elif tag == 0x8825:
|
|
76
|
+
out['gps_present'] = True
|
|
77
|
+
ifd(u32(e + 8), 'gps', depth + 1)
|
|
78
|
+
elif tag in TAG_NAMES:
|
|
79
|
+
v = value(typ, count, e + 8)
|
|
80
|
+
if tag == 0x9C9D and isinstance(v, bytes):
|
|
81
|
+
v = v.decode('utf-16-le', 'replace').strip('\0').strip()
|
|
82
|
+
if isinstance(v, str) and v:
|
|
83
|
+
out[TAG_NAMES[tag]] = v
|
|
84
|
+
except (struct.error, IndexError):
|
|
85
|
+
continue
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
ifd(u32(4), 'main')
|
|
89
|
+
except struct.error:
|
|
90
|
+
pass
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _deg(v):
|
|
95
|
+
try:
|
|
96
|
+
d, m, s = [a / b if b else 0 for a, b in v[:3]]
|
|
97
|
+
return d + m / 60 + s / 3600
|
|
98
|
+
except (TypeError, ValueError, ZeroDivisionError):
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _exif_findings(fields: dict):
|
|
103
|
+
found = []
|
|
104
|
+
lat, lon = _deg(fields.get('gps_lat')), _deg(fields.get('gps_lon'))
|
|
105
|
+
if lat or lon:
|
|
106
|
+
if str(fields.get('gps_lat_ref', 'N')).startswith('S'):
|
|
107
|
+
lat = -lat if lat else lat
|
|
108
|
+
if str(fields.get('gps_lon_ref', 'E')).startswith('W'):
|
|
109
|
+
lon = -lon if lon else lon
|
|
110
|
+
found.append(('media-gps', f'{lat or 0:.2f}, {lon or 0:.2f}'))
|
|
111
|
+
owner = [f'{k}={v}' for k, v in fields.items() if k in OWNER_TAGS]
|
|
112
|
+
if owner:
|
|
113
|
+
found.append(('media-owner', ', '.join(owner)))
|
|
114
|
+
device = ' '.join(v for k, v in fields.items() if k in ('Make', 'Model'))
|
|
115
|
+
if device:
|
|
116
|
+
found.append(('media-device', device))
|
|
117
|
+
return found
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ---------------------------------------------------------------- XMP
|
|
121
|
+
|
|
122
|
+
XMP_CREATOR = re.compile(rb'<dc:creator>.*?</dc:creator>', re.S)
|
|
123
|
+
XMP_GPS = re.compile(rb'exif:GPSLatitude')
|
|
124
|
+
TAG = re.compile(rb'<[^>]+>')
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _xmp(blob: bytes):
|
|
128
|
+
found, texts = [], []
|
|
129
|
+
m = XMP_CREATOR.search(blob)
|
|
130
|
+
if m:
|
|
131
|
+
name = TAG.sub(b' ', m.group(0)).decode('utf-8', 'replace').split()
|
|
132
|
+
if name:
|
|
133
|
+
found.append(('media-owner', 'creator=' + ' '.join(name)))
|
|
134
|
+
if XMP_GPS.search(blob):
|
|
135
|
+
found.append(('media-gps', 'XMP GPS'))
|
|
136
|
+
texts.append(TAG.sub(b' ', blob).decode('utf-8', 'replace'))
|
|
137
|
+
return found, texts
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------- image containers
|
|
141
|
+
|
|
142
|
+
def _jpeg(data: bytes):
|
|
143
|
+
found, texts = [], []
|
|
144
|
+
i = 2
|
|
145
|
+
while i + 4 <= len(data) and data[i] == 0xFF:
|
|
146
|
+
marker = data[i + 1]
|
|
147
|
+
if marker in (0xD9, 0xDA): # end of image, start of scan
|
|
148
|
+
break
|
|
149
|
+
if 0xD0 <= marker <= 0xD7 or marker == 0x01:
|
|
150
|
+
i += 2
|
|
151
|
+
continue
|
|
152
|
+
length = struct.unpack_from('>H', data, i + 2)[0]
|
|
153
|
+
seg = data[i + 4:i + 2 + length]
|
|
154
|
+
if marker == 0xE1 and seg.startswith(b'Exif\0\0'):
|
|
155
|
+
found += _exif_findings(_tiff(seg[6:]))
|
|
156
|
+
elif marker == 0xE1 and seg.startswith(b'http://ns.adobe.com/xap/1.0/'):
|
|
157
|
+
f, t = _xmp(seg)
|
|
158
|
+
found += f
|
|
159
|
+
texts += t
|
|
160
|
+
elif marker == 0xFE: # comment
|
|
161
|
+
texts.append(seg.decode('utf-8', 'replace'))
|
|
162
|
+
i += 2 + length
|
|
163
|
+
return found, texts
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
PNG_REPORT = {'author', 'comment', 'description', 'copyright', 'source', 'disclaimer', 'warning', 'parameters', 'prompt', 'workflow', 'title'}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _png(data: bytes):
|
|
170
|
+
found, texts = [], []
|
|
171
|
+
i = 8
|
|
172
|
+
while i + 8 <= len(data):
|
|
173
|
+
length, kind = struct.unpack_from('>I4s', data, i)
|
|
174
|
+
body = data[i + 8:i + 8 + length]
|
|
175
|
+
i += 12 + length
|
|
176
|
+
try:
|
|
177
|
+
if kind == b'eXIf':
|
|
178
|
+
found += _exif_findings(_tiff(body))
|
|
179
|
+
elif kind in (b'tEXt', b'zTXt', b'iTXt'):
|
|
180
|
+
key, _, rest = body.partition(b'\0')
|
|
181
|
+
if kind == b'zTXt':
|
|
182
|
+
rest = zlib.decompress(rest[1:])
|
|
183
|
+
elif kind == b'iTXt':
|
|
184
|
+
flag, rest = rest[0], rest[2:]
|
|
185
|
+
_lang, _, rest = rest.partition(b'\0')
|
|
186
|
+
_tkey, _, rest = rest.partition(b'\0')
|
|
187
|
+
if flag:
|
|
188
|
+
rest = zlib.decompress(rest)
|
|
189
|
+
keyname = key.decode('latin-1')
|
|
190
|
+
if keyname == 'XML:com.adobe.xmp':
|
|
191
|
+
f, t = _xmp(rest)
|
|
192
|
+
found += f
|
|
193
|
+
texts += t
|
|
194
|
+
continue
|
|
195
|
+
text = rest.decode('utf-8', 'replace')
|
|
196
|
+
texts.append(text)
|
|
197
|
+
if keyname.lower() in PNG_REPORT and text.strip():
|
|
198
|
+
found.append(('media-text', f'{keyname}: {text.strip()[:80]}'))
|
|
199
|
+
except (zlib.error, IndexError, ValueError):
|
|
200
|
+
continue
|
|
201
|
+
if kind == b'IEND':
|
|
202
|
+
break
|
|
203
|
+
return found, texts
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _webp(data: bytes):
|
|
207
|
+
found, texts = [], []
|
|
208
|
+
i = 12
|
|
209
|
+
while i + 8 <= len(data):
|
|
210
|
+
kind, length = data[i:i + 4], struct.unpack_from('<I', data, i + 4)[0]
|
|
211
|
+
body = data[i + 8:i + 8 + length]
|
|
212
|
+
if kind == b'EXIF':
|
|
213
|
+
found += _exif_findings(_tiff(body[6:] if body.startswith(b'Exif\0\0') else body))
|
|
214
|
+
elif kind == b'XMP ':
|
|
215
|
+
f, t = _xmp(body)
|
|
216
|
+
found += f
|
|
217
|
+
texts += t
|
|
218
|
+
i += 8 + length + (length & 1)
|
|
219
|
+
return found, texts
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _search_exif(data: bytes):
|
|
223
|
+
"""HEIC/AVIF and anything else: find an EXIF block by its header."""
|
|
224
|
+
found, texts = [], []
|
|
225
|
+
k = data.find(b'Exif\0\0')
|
|
226
|
+
if k >= 0:
|
|
227
|
+
found += _exif_findings(_tiff(data[k + 6:]))
|
|
228
|
+
k = data.find(b'<x:xmpmeta')
|
|
229
|
+
if k >= 0:
|
|
230
|
+
f, t = _xmp(data[k:k + 200_000])
|
|
231
|
+
found += f
|
|
232
|
+
texts += t
|
|
233
|
+
return found, texts
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ---------------------------------------------------------------- documents
|
|
237
|
+
|
|
238
|
+
PDF_AUTHOR = re.compile(rb'/Author\s*(\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>)')
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _pdf_string(raw: bytes) -> str:
|
|
242
|
+
if raw.startswith(b'<'):
|
|
243
|
+
b = bytes.fromhex(re.sub(rb'\s', b'', raw[1:-1]).decode())
|
|
244
|
+
else:
|
|
245
|
+
b = re.sub(rb'\\(.)', rb'\1', raw[1:-1])
|
|
246
|
+
if b.startswith(b'\xfe\xff'):
|
|
247
|
+
return b[2:].decode('utf-16-be', 'replace')
|
|
248
|
+
return b.decode('latin-1')
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _pdf(data: bytes):
|
|
252
|
+
found, texts = [], []
|
|
253
|
+
for m in PDF_AUTHOR.finditer(data):
|
|
254
|
+
try:
|
|
255
|
+
name = _pdf_string(m.group(1)).strip()
|
|
256
|
+
except ValueError:
|
|
257
|
+
continue
|
|
258
|
+
if name:
|
|
259
|
+
found.append(('document-author', 'Author=' + name))
|
|
260
|
+
texts.append(name)
|
|
261
|
+
break
|
|
262
|
+
k = data.find(b'<x:xmpmeta')
|
|
263
|
+
if k >= 0:
|
|
264
|
+
f, t = _xmp(data[k:k + 200_000])
|
|
265
|
+
found += [('document-author', d) if r == 'media-owner' else (r, d) for r, d in f]
|
|
266
|
+
texts += t
|
|
267
|
+
return found, texts
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
OOXML_FIELDS = {
|
|
271
|
+
'docProps/core.xml': [rb'<dc:creator>(.*?)</dc:creator>', rb'<cp:lastModifiedBy>(.*?)</cp:lastModifiedBy>'],
|
|
272
|
+
'docProps/app.xml': [rb'<Company>(.*?)</Company>', rb'<Manager>(.*?)</Manager>'],
|
|
273
|
+
'meta.xml': [rb'<meta:initial-creator>(.*?)</meta:initial-creator>', rb'<dc:creator>(.*?)</dc:creator>'],
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _office(data: bytes):
|
|
278
|
+
found, texts = [], []
|
|
279
|
+
try:
|
|
280
|
+
z = zipfile.ZipFile(io.BytesIO(data))
|
|
281
|
+
except zipfile.BadZipFile:
|
|
282
|
+
return found, texts
|
|
283
|
+
values = []
|
|
284
|
+
for part, pats in OOXML_FIELDS.items():
|
|
285
|
+
try:
|
|
286
|
+
xml = z.read(part)
|
|
287
|
+
except KeyError:
|
|
288
|
+
continue
|
|
289
|
+
for p in pats:
|
|
290
|
+
m = re.search(p, xml, re.S)
|
|
291
|
+
if m and m.group(1).strip():
|
|
292
|
+
values.append(m.group(1).decode('utf-8', 'replace').strip())
|
|
293
|
+
if values:
|
|
294
|
+
found.append(('document-author', ', '.join(dict.fromkeys(values))))
|
|
295
|
+
texts += values
|
|
296
|
+
return found, texts
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def inspect(name: str, data: bytes):
|
|
300
|
+
lower = name.lower()
|
|
301
|
+
try:
|
|
302
|
+
if data[:3] == b'\xff\xd8\xff':
|
|
303
|
+
return _jpeg(data)
|
|
304
|
+
if data[:8] == b'\x89PNG\r\n\x1a\n':
|
|
305
|
+
return _png(data)
|
|
306
|
+
if data[:4] == b'RIFF' and data[8:12] == b'WEBP':
|
|
307
|
+
return _webp(data)
|
|
308
|
+
if data[:4] in (b'II*\0', b'MM\0*'):
|
|
309
|
+
return _exif_findings(_tiff(data)), []
|
|
310
|
+
if data[:5] == b'%PDF-':
|
|
311
|
+
return _pdf(data)
|
|
312
|
+
if data[:2] == b'PK' and re.search(r'\.(?:docx|docm|xlsx|xlsm|pptx|pptm|odt|ods|odp)$', lower):
|
|
313
|
+
return _office(data)
|
|
314
|
+
if re.search(r'\.(?:heic|heif|avif)$', lower):
|
|
315
|
+
return _search_exif(data)
|
|
316
|
+
except (struct.error, IndexError, ValueError):
|
|
317
|
+
pass
|
|
318
|
+
return [], []
|