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.

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