-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfix_insecure.py
107 lines (83 loc) · 2.88 KB
/
fix_insecure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import logging
import re
log = logging.getLogger(__name__)
def main(stdin, cwd, urlopener):
web = WebCheck(urlopener)
pages = Pages(cwd / 'pages')
for page, img in grok(stdin):
doc = pages.doc(page)
if not doc.exists():
log.warn('cannot find doc for %s at %s', path, str(doc))
continue
if img not in doc.open().read():
# assume we did it on a previous pass
continue
for addr in [img, re.sub('^http:', 'https:', img)]:
try:
dest = web.geturl(addr)
except Exception as lose:
log.warn('cannot geturl for %s: %s', addr, lose)
else:
if dest == img or not dest.startswith('https:'):
continue
pages.edit(doc, img, dest)
def grok(lines):
path = None
urls = None
for line in lines:
m = re.search(r'Mixed content detected in: (?P<path>.*)', line)
if m:
path = m.group('path')
elif '--> insecure img urls:' in line:
pass
else:
m = re.search(r' - (?P<url>http.*)', line)
if m:
url = m.group('url')
yield path, url
class WebCheck(object):
def __init__(self, urlopener):
self.__urlopener = urlopener
def geturl(self, img):
log.info('opening %s ...', img)
# addr = img.replace('http:', 'https:')
response = self.__urlopener.open(img)
return response.geturl()
class Pages(object):
def __init__(self, store):
self.__store = store
def doc(self, path):
store = self.__store
tail = re.sub('^/', '', path)
return (store / tail).with_suffix('.md')
@classmethod
def edit(cls, doc, target, replacement):
with doc.open('rb+') as fp:
content = fp.read().replace(target, replacement)
fp.seek(0)
fp.write(content)
log.info('edited %s', doc)
class Path(object):
def __init__(self, here,
open, joinpath, exists):
self.path = here
self.exists = lambda: exists(here)
self.open = lambda mode='rb': open(here, mode=mode)
make = lambda there: Path(there, open, joinpath, exists)
self.joinpath = lambda other: make(joinpath(here, other))
self.with_suffix = lambda suffix: make(here.rsplit('.', 1)[0] + suffix)
def __repr__(self):
return self.path
def __div__(self, other):
return self.joinpath(other)
if __name__ == '__main__':
def _script():
from io import open as io_open
from sys import stdin
from os.path import join as joinpath, exists
from urllib2 import build_opener
logging.basicConfig(level=logging.DEBUG)
cwd = Path('.',
io_open, joinpath, exists)
main(stdin, cwd, build_opener())
_script()