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.

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