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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
|
#!/usr/bin/env python
# vim:fileencoding=utf-8
# Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import re
import string
from ._entities import html5_entities
from .polyglot import codepoint_to_chr
space_chars = frozenset(("\t", "\n", "\u000C", " ", "\r"))
space_chars_bytes = frozenset(item.encode("ascii") for item in space_chars)
ascii_letters_bytes = frozenset(
item.encode("ascii") for item in string.ascii_letters)
spaces_angle_brackets = space_chars_bytes | frozenset((b">", b"<"))
skip1 = space_chars_bytes | frozenset((b"/", ))
head_elems = frozenset((
b"html", b"head", b"title", b"base", b"script",
b"style", b"meta", b"link", b"object"))
def my_unichr(num):
try:
return codepoint_to_chr(num)
except (ValueError, OverflowError):
return '?'
def replace_entity(match):
ent = match.group(1).lower()
if ent in {'apos', 'squot'}:
# squot is generated by some broken CMS software
return "'"
if ent == 'hellips':
ent = 'hellip'
if ent.startswith('#'):
try:
if ent[1] in ('x', 'X'):
num = int(ent[2:], 16)
else:
num = int(ent[1:])
except Exception:
return '&' + ent + ';'
if num > 255:
return my_unichr(num)
try:
return chr(num).decode('cp1252')
except UnicodeDecodeError:
return my_unichr(num)
try:
return html5_entities[ent]
except KeyError:
pass
return '&' + ent + ';'
class Bytes(bytes):
"""String-like object with an associated position and various extra methods
If the position is ever greater than the string length then an exception is
raised"""
def __init__(self, value):
self._position = -1
def __iter__(self):
return self
def __next__(self):
p = self._position = self._position + 1
if p >= len(self):
raise StopIteration
elif p < 0:
raise TypeError
return self[p:p + 1]
def next(self):
# Py2 compat
return self.__next__()
def previous(self):
p = self._position
if p >= len(self):
raise StopIteration
elif p < 0:
raise TypeError
self._position = p = p - 1
return self[p:p + 1]
@property
def position(self):
if self._position >= len(self):
raise StopIteration
if self._position >= 0:
return self._position
@position.setter
def position(self, position):
if self._position >= len(self):
raise StopIteration
self._position = position
@property
def current_byte(self):
return self[self.position:self.position + 1]
def skip(self, chars=space_chars_bytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return
def skip_until(self, chars):
p = pos = self.position
while p < len(self):
c = self[p:p + 1]
if c in chars:
self._position = p
return self[pos:p], c
p += 1
self._position = p
return b'', b''
def match_bytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv
def match_bytes_pat(self, pat):
bytes = pat.pattern
m = pat.match(self, self.position)
if m is None:
return False
bytes = m.group()
self.position += len(bytes)
return True
def jump_to(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
new_pos = self.find(bytes, max(0, self.position))
if new_pos > -1:
new_pos -= self.position
if self._position == -1:
self._position = 0
self._position += (new_pos + len(bytes) - 1)
return True
else:
raise StopIteration
class HTTPEquivParser(object):
"""Mini parser for detecting http-equiv headers from meta tags """
def __init__(self, data):
"""string - the data to work on """
self.data = Bytes(data)
self.headers = []
def __call__(self):
mb, mbp = self.data.match_bytes, self.data.match_bytes_pat
dispatch = (
(mb, b"<!--", self.handle_comment),
(mbp, re.compile(b"<meta", flags=re.IGNORECASE),
self.handle_meta),
(mbp, re.compile(b"</head", flags=re.IGNORECASE),
lambda: False),
(mb, b"</", self.handle_possible_end_tag),
(mb, b"<!", self.handle_other),
(mb, b"<?", self.handle_other),
(mb, b"<", self.handle_possible_start_tag)
)
for byte in self.data:
keep_parsing = True
for matcher, key, method in dispatch:
if matcher(key):
try:
keep_parsing = method()
break
except StopIteration:
keep_parsing = False
break
if not keep_parsing:
break
ans = []
entity_pat = re.compile(r'&(\S+?);')
for name, val in self.headers:
try:
name, val = name.decode('ascii'), val.decode('ascii')
except ValueError:
continue
name = entity_pat.sub(replace_entity, name)
val = entity_pat.sub(replace_entity, val)
try:
name, val = name.encode('ascii'), val.encode('ascii')
except ValueError:
continue
ans.append((name, val))
return ans
def handle_comment(self):
"""Skip over comments"""
return self.data.jump_to(b"-->")
def handle_meta(self):
if self.data.current_byte not in space_chars_bytes:
# if we have <meta not followed by a space so just keep going
return True
# We have a valid meta element we want to search for attributes
pending_header = pending_content = None
while True:
# Try to find the next attribute after the current position
attr = self.get_attribute()
if attr is None:
return True
name, val = attr
name = name.lower()
if name == b"http-equiv":
if val:
val = val.lower()
if pending_content:
self.headers.append((val, pending_content))
return True
pending_header = val
elif name == b'content':
if val:
if pending_header:
self.headers.append((pending_header, val))
return True
pending_content = val
return True
def handle_possible_start_tag(self):
return self.handle_possible_tag(False)
def handle_possible_end_tag(self):
next(self.data)
return self.handle_possible_tag(True)
def handle_possible_tag(self, end_tag):
data = self.data
if data.current_byte not in ascii_letters_bytes:
# If the next byte is not an ascii letter either ignore this
# fragment (possible start tag case) or treat it according to
# handle_other
if end_tag:
data.previous()
self.handle_other()
return True
tag_name, c = data.skip_until(spaces_angle_brackets)
tag_name = tag_name.lower()
if not end_tag and tag_name not in head_elems:
return False
if c == b"<":
# return to the first step in the overall "two step" algorithm
# reprocessing the < byte
data.previous()
else:
# Read all attributes
attr = self.get_attribute()
while attr is not None:
attr = self.get_attribute()
return True
def handle_other(self):
return self.data.jump_to(b">")
def get_attribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(skip1)
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attr_name = []
attr_value = []
# Step 4 attribute name
while True:
if c == b"=" and attr_name:
break
elif c in space_chars_bytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attr_name), b""
elif c is None:
return None
else:
attr_name.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attr_name), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quote_char = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quote_char:
next(data)
return b"".join(attr_name), b"".join(attr_value)
# 10.4
else:
attr_value.append(c)
elif c == b">":
return b"".join(attr_name), b""
elif c is None:
return None
else:
attr_value.append(c)
# Step 11
while True:
c = next(data)
if c in spaces_angle_brackets:
return b"".join(attr_name), b"".join(attr_value)
elif c is None:
return None
else:
attr_value.append(c)
|