A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

488 lines
19 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import base64
  23. import collections
  24. from collections import deque
  25. import functools
  26. from gzip import GzipFile
  27. from http.client import HTTPException
  28. from logging import getLogger
  29. from math import log
  30. from queue import Empty, Queue
  31. from socket import error as socket_error
  32. from io import StringIO
  33. from struct import error as struct_error
  34. from threading import Lock, Thread
  35. import time
  36. from urllib.error import URLError
  37. import urllib.parse
  38. from urllib.request import build_opener, Request
  39. from earwigbot import importer
  40. from earwigbot.exceptions import ParserExclusionError, ParserRedirectError
  41. from earwigbot.wiki.copyvios.markov import MarkovChain, MarkovChainIntersection
  42. from earwigbot.wiki.copyvios.parsers import get_parser
  43. from earwigbot.wiki.copyvios.result import CopyvioCheckResult, CopyvioSource
  44. tldextract = importer.new("tldextract")
  45. __all__ = ["globalize", "localize", "CopyvioWorkspace"]
  46. _MAX_REDIRECTS = 3
  47. _MAX_RAW_SIZE = 20 * 1024 ** 2
  48. _is_globalized = False
  49. _global_queues = None
  50. _global_workers = []
  51. _OpenedURL = collections.namedtuple('_OpenedURL', ['content', 'parser_class'])
  52. def globalize(num_workers=8):
  53. """Cause all copyvio checks to be done by one global set of workers.
  54. This is useful when checks are being done through a web interface where
  55. large numbers of simulatenous requests could be problematic. The global
  56. workers are spawned when the function is called, run continuously, and
  57. intelligently handle multiple checks.
  58. This function is not thread-safe and should only be called when no checks
  59. are being done. It has no effect if it has already been called.
  60. """
  61. global _is_globalized, _global_queues
  62. if _is_globalized:
  63. return
  64. _global_queues = _CopyvioQueues()
  65. for i in range(num_workers):
  66. worker = _CopyvioWorker("global-{0}".format(i), _global_queues)
  67. worker.start()
  68. _global_workers.append(worker)
  69. _is_globalized = True
  70. def localize():
  71. """Return to using page-specific workers for copyvio checks.
  72. This disables changes made by :func:`globalize`, including stoping the
  73. global worker threads.
  74. This function is not thread-safe and should only be called when no checks
  75. are being done.
  76. """
  77. global _is_globalized, _global_queues, _global_workers
  78. if not _is_globalized:
  79. return
  80. for i in range(len(_global_workers)):
  81. _global_queues.unassigned.put((StopIteration, None))
  82. _global_queues = None
  83. _global_workers = []
  84. _is_globalized = False
  85. class _CopyvioQueues:
  86. """Stores data necessary to maintain the various queues during a check."""
  87. def __init__(self):
  88. self.lock = Lock()
  89. self.sites = {}
  90. self.unassigned = Queue()
  91. class _CopyvioWorker:
  92. """A multithreaded URL opener/parser instance."""
  93. def __init__(self, name, queues, until=None):
  94. self._name = name
  95. self._queues = queues
  96. self._until = until
  97. self._site = None
  98. self._queue = None
  99. self._search_config = None
  100. self._opener = build_opener()
  101. self._logger = getLogger("earwigbot.wiki.cvworker." + name)
  102. def _try_map_proxy_url(self, url, parsed, extra_headers, is_error=False):
  103. if not self._search_config or "proxies" not in self._search_config:
  104. return url, False
  105. for proxy_info in self._search_config["proxies"]:
  106. if parsed.netloc != proxy_info["netloc"]:
  107. continue
  108. if "onerr" in proxy_info:
  109. if proxy_info["onerr"] and not is_error:
  110. continue
  111. if not proxy_info["onerr"] and is_error:
  112. continue
  113. path = parsed.path
  114. if "path" in proxy_info:
  115. if not parsed.path.startswith(proxy_info["path"]):
  116. continue
  117. path = path[len(proxy_info["path"]):]
  118. url = proxy_info["target"] + path
  119. if "auth" in proxy_info:
  120. extra_headers["Authorization"] = "Basic %s" % (
  121. base64.b64encode(proxy_info["auth"]))
  122. return url, True
  123. return url, False
  124. def _open_url_raw(self, url, timeout=5, allow_content_types=None):
  125. """Open a URL, without parsing it.
  126. None will be returned for URLs that cannot be read for whatever reason.
  127. """
  128. parsed = urllib.parse.urlparse(url)
  129. if not isinstance(url, str):
  130. url = url.encode("utf8")
  131. extra_headers = {}
  132. url, _ = self._try_map_proxy_url(url, parsed, extra_headers)
  133. request = Request(url, headers=extra_headers)
  134. try:
  135. response = self._opener.open(request, timeout=timeout)
  136. except (URLError, HTTPException, socket_error, ValueError):
  137. url, remapped = self._try_map_proxy_url(url, parsed, extra_headers, is_error=True)
  138. if not remapped:
  139. self._logger.exception("Failed to fetch URL: %s", url)
  140. return None
  141. self._logger.info("Failed to fetch URL, trying proxy remap: %s", url)
  142. request = Request(url, headers=extra_headers)
  143. try:
  144. response = self._opener.open(request, timeout=timeout)
  145. except (URLError, HTTPException, socket_error, ValueError):
  146. self._logger.exception("Failed to fetch URL after proxy remap: %s", url)
  147. return None
  148. try:
  149. size = int(response.headers.get("Content-Length", 0))
  150. except ValueError:
  151. return None
  152. content_type = response.headers.get("Content-Type", "text/plain")
  153. content_type = content_type.split(";", 1)[0]
  154. parser_class = get_parser(content_type)
  155. if not parser_class and (
  156. not allow_content_types or content_type not in allow_content_types):
  157. return None
  158. if not parser_class:
  159. parser_class = get_parser("text/plain")
  160. if size > (15 if parser_class.TYPE == "PDF" else 2) * 1024 ** 2:
  161. return None
  162. try:
  163. # Additional safety check for pages using Transfer-Encoding: chunked
  164. # where we can't read the Content-Length
  165. content = response.read(_MAX_RAW_SIZE + 1)
  166. except (URLError, socket_error):
  167. return None
  168. if len(content) > _MAX_RAW_SIZE:
  169. return None
  170. if response.headers.get("Content-Encoding") == "gzip":
  171. stream = StringIO(content)
  172. gzipper = GzipFile(fileobj=stream)
  173. try:
  174. content = gzipper.read()
  175. except (IOError, struct_error):
  176. return None
  177. if len(content) > _MAX_RAW_SIZE:
  178. return None
  179. return _OpenedURL(content, parser_class)
  180. def _open_url(self, source, redirects=0):
  181. """Open a URL and return its parsed content, or None.
  182. First, we will decompress the content if the headers contain "gzip" as
  183. its content encoding. Then, we will return the content stripped using
  184. an HTML parser if the headers indicate it is HTML, or return the
  185. content directly if it is plain text. If we don't understand the
  186. content type, we'll return None.
  187. If a URLError was raised while opening the URL or an IOError was raised
  188. while decompressing, None will be returned.
  189. """
  190. self._search_config = source.search_config
  191. if source.headers:
  192. self._opener.addheaders = source.headers
  193. result = self._open_url_raw(source.url, timeout=source.timeout)
  194. if result is None:
  195. return None
  196. args = source.parser_args.copy() if source.parser_args else {}
  197. args["open_url"] = functools.partial(self._open_url_raw, timeout=source.timeout)
  198. parser = result.parser_class(result.content, url=source.url, args=args)
  199. try:
  200. return parser.parse()
  201. except ParserRedirectError as exc:
  202. if redirects >= _MAX_REDIRECTS:
  203. return None
  204. source.url = exc.url.decode("utf8")
  205. return self._open_url(source, redirects=redirects + 1)
  206. def _acquire_new_site(self):
  207. """Block for a new unassigned site queue."""
  208. if self._until:
  209. timeout = self._until - time.time()
  210. if timeout <= 0:
  211. raise Empty
  212. else:
  213. timeout = None
  214. self._logger.debug("Waiting for new site queue")
  215. site, queue = self._queues.unassigned.get(timeout=timeout)
  216. if site is StopIteration:
  217. raise StopIteration
  218. self._logger.debug("Acquired new site queue: {0}".format(site))
  219. self._site = site
  220. self._queue = queue
  221. def _dequeue(self):
  222. """Remove a source from one of the queues."""
  223. if not self._site:
  224. self._acquire_new_site()
  225. logmsg = "Fetching source URL from queue {0}"
  226. self._logger.debug(logmsg.format(self._site))
  227. self._queues.lock.acquire()
  228. try:
  229. source = self._queue.popleft()
  230. except IndexError:
  231. self._logger.debug("Queue is empty")
  232. del self._queues.sites[self._site]
  233. self._site = None
  234. self._queue = None
  235. self._queues.lock.release()
  236. return self._dequeue()
  237. self._logger.debug("Got source URL: {0}".format(source.url))
  238. if source.skipped:
  239. self._logger.debug("Source has been skipped")
  240. self._queues.lock.release()
  241. return self._dequeue()
  242. source.start_work()
  243. self._queues.lock.release()
  244. return source
  245. def _handle_once(self):
  246. """Handle a single source from one of the queues."""
  247. try:
  248. source = self._dequeue()
  249. except Empty:
  250. self._logger.debug("Exiting: queue timed out")
  251. return False
  252. except StopIteration:
  253. self._logger.debug("Exiting: got stop signal")
  254. return False
  255. try:
  256. text = self._open_url(source)
  257. except ParserExclusionError:
  258. self._logger.debug("Source excluded by content parser")
  259. source.skipped = source.excluded = True
  260. source.finish_work()
  261. except Exception:
  262. self._logger.exception("Uncaught exception in worker")
  263. source.skip()
  264. source.finish_work()
  265. else:
  266. chain = MarkovChain(text) if text else None
  267. source.workspace.compare(source, chain)
  268. return True
  269. def _run(self):
  270. """Main entry point for the worker thread.
  271. We will keep fetching URLs from the queues and handling them until
  272. either we run out of time, or we get an exit signal that the queue is
  273. now empty.
  274. """
  275. while True:
  276. try:
  277. if not self._handle_once():
  278. break
  279. except Exception:
  280. self._logger.exception("Uncaught exception in worker")
  281. time.sleep(5) # Delay if we get stuck in a busy loop
  282. def start(self):
  283. """Start the copyvio worker in a new thread."""
  284. thread = Thread(target=self._run, name="cvworker-" + self._name)
  285. thread.daemon = True
  286. thread.start()
  287. class CopyvioWorkspace:
  288. """Manages a single copyvio check distributed across threads."""
  289. def __init__(self, article, min_confidence, max_time, logger, headers,
  290. url_timeout=5, num_workers=8, short_circuit=True,
  291. parser_args=None, exclude_check=None, config=None):
  292. self.sources = []
  293. self.finished = False
  294. self.possible_miss = False
  295. self._article = article
  296. self._logger = logger.getChild("copyvios")
  297. self._min_confidence = min_confidence
  298. self._start_time = time.time()
  299. self._until = (self._start_time + max_time) if max_time > 0 else None
  300. self._handled_urls = set()
  301. self._finish_lock = Lock()
  302. self._short_circuit = short_circuit
  303. self._source_args = {
  304. "workspace": self, "headers": headers, "timeout": url_timeout,
  305. "parser_args": parser_args, "search_config": config}
  306. self._exclude_check = exclude_check
  307. if _is_globalized:
  308. self._queues = _global_queues
  309. else:
  310. self._queues = _CopyvioQueues()
  311. self._num_workers = num_workers
  312. for i in range(num_workers):
  313. name = "local-{0:04}.{1}".format(id(self) % 10000, i)
  314. _CopyvioWorker(name, self._queues, self._until).start()
  315. def _calculate_confidence(self, delta):
  316. """Return the confidence of a violation as a float between 0 and 1."""
  317. def conf_with_article_and_delta(article, delta):
  318. """Calculate confidence using the article and delta chain sizes."""
  319. # This piecewise function exhibits exponential growth until it
  320. # reaches the default "suspect" confidence threshold, at which
  321. # point it transitions to polynomial growth with a limit of 1 as
  322. # (delta / article) approaches 1.
  323. # A graph can be viewed here: https://goo.gl/mKPhvr
  324. ratio = delta / article
  325. if ratio <= 0.52763:
  326. return -log(1 - ratio)
  327. else:
  328. return (-0.8939 * (ratio ** 2)) + (1.8948 * ratio) - 0.0009
  329. def conf_with_delta(delta):
  330. """Calculate confidence using just the delta chain size."""
  331. # This piecewise function was derived from experimental data using
  332. # reference points at (0, 0), (100, 0.5), (250, 0.75), (500, 0.9),
  333. # and (1000, 0.95), with a limit of 1 as delta approaches infinity.
  334. # A graph can be viewed here: https://goo.gl/lVl7or
  335. if delta <= 100:
  336. return delta / (delta + 100)
  337. elif delta <= 250:
  338. return (delta - 25) / (delta + 50)
  339. elif delta <= 500:
  340. return (10.5 * delta - 750) / (10 * delta)
  341. else:
  342. return (delta - 50) / delta
  343. d_size = float(delta.size)
  344. return abs(max(conf_with_article_and_delta(self._article.size, d_size),
  345. conf_with_delta(d_size)))
  346. def _finish_early(self):
  347. """Finish handling links prematurely (if we've hit min_confidence)."""
  348. self._logger.debug("Confidence threshold met; skipping remaining sources")
  349. with self._queues.lock:
  350. for source in self.sources:
  351. source.skip()
  352. self.finished = True
  353. def enqueue(self, urls):
  354. """Put a list of URLs into the various worker queues."""
  355. for url in urls:
  356. with self._queues.lock:
  357. if url in self._handled_urls:
  358. continue
  359. self._handled_urls.add(url)
  360. source = CopyvioSource(url=url, **self._source_args)
  361. self.sources.append(source)
  362. if self._exclude_check and self._exclude_check(url):
  363. self._logger.debug("enqueue(): exclude {0}".format(url))
  364. source.excluded = True
  365. source.skip()
  366. continue
  367. if self._short_circuit and self.finished:
  368. self._logger.debug("enqueue(): auto-skip {0}".format(url))
  369. source.skip()
  370. continue
  371. try:
  372. key = tldextract.extract(url).registered_domain
  373. except ImportError: # Fall back on very naive method
  374. from urllib.parse import urlparse
  375. key = ".".join(urlparse(url).netloc.split(".")[-2:])
  376. logmsg = "enqueue(): {0} {1} -> {2}"
  377. if key in self._queues.sites:
  378. self._logger.debug(logmsg.format("append", key, url))
  379. self._queues.sites[key].append(source)
  380. else:
  381. self._logger.debug(logmsg.format("new", key, url))
  382. self._queues.sites[key] = queue = deque()
  383. queue.append(source)
  384. self._queues.unassigned.put((key, queue))
  385. def compare(self, source, source_chain):
  386. """Compare a source to the article; call _finish_early if necessary."""
  387. if source_chain:
  388. delta = MarkovChainIntersection(self._article, source_chain)
  389. conf = self._calculate_confidence(delta)
  390. else:
  391. conf = 0.0
  392. self._logger.debug("compare(): {0} -> {1}".format(source.url, conf))
  393. with self._finish_lock:
  394. if source_chain:
  395. source.update(conf, source_chain, delta)
  396. source.finish_work()
  397. if not self.finished and conf >= self._min_confidence:
  398. if self._short_circuit:
  399. self._finish_early()
  400. else:
  401. self.finished = True
  402. def wait(self):
  403. """Wait for the workers to finish handling the sources."""
  404. self._logger.debug("Waiting on {0} sources".format(len(self.sources)))
  405. for source in self.sources:
  406. source.join(self._until)
  407. with self._finish_lock:
  408. pass # Wait for any remaining comparisons to be finished
  409. if not _is_globalized:
  410. for i in range(self._num_workers):
  411. self._queues.unassigned.put((StopIteration, None))
  412. def get_result(self, num_queries=0):
  413. """Return a CopyvioCheckResult containing the results of this check."""
  414. def cmpfunc(s1, s2):
  415. if s2.confidence != s1.confidence:
  416. return 1 if s2.confidence > s1.confidence else -1
  417. if s2.excluded != s1.excluded:
  418. return 1 if s1.excluded else -1
  419. return int(s1.skipped) - int(s2.skipped)
  420. self.sources.sort(cmpfunc)
  421. return CopyvioCheckResult(self.finished, self.sources, num_queries,
  422. time.time() - self._start_time, self._article,
  423. self.possible_miss)