tbtools.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. from __future__ import annotations
  2. import itertools
  3. import linecache
  4. import os
  5. import re
  6. import sys
  7. import sysconfig
  8. import traceback
  9. import typing as t
  10. from markupsafe import escape
  11. from ..utils import cached_property
  12. from .console import Console
  13. HEADER = """\
  14. <!doctype html>
  15. <html lang=en>
  16. <head>
  17. <title>%(title)s // Werkzeug Debugger</title>
  18. <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css">
  19. <link rel="shortcut icon"
  20. href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
  21. <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
  22. <script>
  23. var CONSOLE_MODE = %(console)s,
  24. EVALEX = %(evalex)s,
  25. EVALEX_TRUSTED = %(evalex_trusted)s,
  26. SECRET = "%(secret)s";
  27. </script>
  28. </head>
  29. <body style="background-color: #fff">
  30. <div class="debugger">
  31. """
  32. FOOTER = """\
  33. <div class="footer">
  34. Brought to you by <strong class="arthur">DON'T PANIC</strong>, your
  35. friendly Werkzeug powered traceback interpreter.
  36. </div>
  37. </div>
  38. <div class="pin-prompt">
  39. <div class="inner">
  40. <h3>Console Locked</h3>
  41. <p>
  42. The console is locked and needs to be unlocked by entering the PIN.
  43. You can find the PIN printed out on the standard output of your
  44. shell that runs the server.
  45. <form>
  46. <p>PIN:
  47. <input type=text name=pin size=14>
  48. <input type=submit name=btn value="Confirm Pin">
  49. </form>
  50. </div>
  51. </div>
  52. </body>
  53. </html>
  54. """
  55. PAGE_HTML = (
  56. HEADER
  57. + """\
  58. <h1>%(exception_type)s</h1>
  59. <div class="detail">
  60. <p class="errormsg">%(exception)s</p>
  61. </div>
  62. <h2 class="traceback">Traceback <em>(most recent call last)</em></h2>
  63. %(summary)s
  64. <div class="plain">
  65. <p>
  66. This is the Copy/Paste friendly version of the traceback.
  67. </p>
  68. <textarea cols="50" rows="10" name="code" readonly>%(plaintext)s</textarea>
  69. </div>
  70. <div class="explanation">
  71. The debugger caught an exception in your WSGI application. You can now
  72. look at the traceback which led to the error. <span class="nojavascript">
  73. If you enable JavaScript you can also use additional features such as code
  74. execution (if the evalex feature is enabled), automatic pasting of the
  75. exceptions and much more.</span>
  76. </div>
  77. """
  78. + FOOTER
  79. + """
  80. <!--
  81. %(plaintext_cs)s
  82. -->
  83. """
  84. )
  85. CONSOLE_HTML = (
  86. HEADER
  87. + """\
  88. <h1>Interactive Console</h1>
  89. <div class="explanation">
  90. In this console you can execute Python expressions in the context of the
  91. application. The initial namespace was created by the debugger automatically.
  92. </div>
  93. <div class="console"><div class="inner">The Console requires JavaScript.</div></div>
  94. """
  95. + FOOTER
  96. )
  97. SUMMARY_HTML = """\
  98. <div class="%(classes)s">
  99. %(title)s
  100. <ul>%(frames)s</ul>
  101. %(description)s
  102. </div>
  103. """
  104. FRAME_HTML = """\
  105. <div class="frame" id="frame-%(id)d">
  106. <h4>File <cite class="filename">"%(filename)s"</cite>,
  107. line <em class="line">%(lineno)s</em>,
  108. in <code class="function">%(function_name)s</code></h4>
  109. <div class="source %(library)s">%(lines)s</div>
  110. </div>
  111. """
  112. def _process_traceback(
  113. exc: BaseException,
  114. te: traceback.TracebackException | None = None,
  115. *,
  116. skip: int = 0,
  117. hide: bool = True,
  118. ) -> traceback.TracebackException:
  119. if te is None:
  120. te = traceback.TracebackException.from_exception(exc, lookup_lines=False)
  121. # Get the frames the same way StackSummary.extract did, in order
  122. # to match each frame with the FrameSummary to augment.
  123. frame_gen = traceback.walk_tb(exc.__traceback__)
  124. limit = getattr(sys, "tracebacklimit", None)
  125. if limit is not None:
  126. if limit < 0:
  127. limit = 0
  128. frame_gen = itertools.islice(frame_gen, limit)
  129. if skip:
  130. frame_gen = itertools.islice(frame_gen, skip, None)
  131. del te.stack[:skip]
  132. new_stack: list[DebugFrameSummary] = []
  133. hidden = False
  134. # Match each frame with the FrameSummary that was generated.
  135. # Hide frames using Paste's __traceback_hide__ rules. Replace
  136. # all visible FrameSummary with DebugFrameSummary.
  137. for (f, _), fs in zip(frame_gen, te.stack):
  138. if hide:
  139. hide_value = f.f_locals.get("__traceback_hide__", False)
  140. if hide_value in {"before", "before_and_this"}:
  141. new_stack = []
  142. hidden = False
  143. if hide_value == "before_and_this":
  144. continue
  145. elif hide_value in {"reset", "reset_and_this"}:
  146. hidden = False
  147. if hide_value == "reset_and_this":
  148. continue
  149. elif hide_value in {"after", "after_and_this"}:
  150. hidden = True
  151. if hide_value == "after_and_this":
  152. continue
  153. elif hide_value or hidden:
  154. continue
  155. frame_args: dict[str, t.Any] = {
  156. "filename": fs.filename,
  157. "lineno": fs.lineno,
  158. "name": fs.name,
  159. "locals": f.f_locals,
  160. "globals": f.f_globals,
  161. }
  162. if hasattr(fs, "colno"):
  163. frame_args["colno"] = fs.colno
  164. frame_args["end_colno"] = fs.end_colno # type: ignore[attr-defined]
  165. new_stack.append(DebugFrameSummary(**frame_args))
  166. # The codeop module is used to compile code from the interactive
  167. # debugger. Hide any codeop frames from the bottom of the traceback.
  168. while new_stack:
  169. module = new_stack[0].global_ns.get("__name__")
  170. if module is None:
  171. module = new_stack[0].local_ns.get("__name__")
  172. if module == "codeop":
  173. del new_stack[0]
  174. else:
  175. break
  176. te.stack[:] = new_stack
  177. if te.__context__:
  178. context_exc = t.cast(BaseException, exc.__context__)
  179. te.__context__ = _process_traceback(context_exc, te.__context__, hide=hide)
  180. if te.__cause__:
  181. cause_exc = t.cast(BaseException, exc.__cause__)
  182. te.__cause__ = _process_traceback(cause_exc, te.__cause__, hide=hide)
  183. return te
  184. class DebugTraceback:
  185. __slots__ = ("_te", "_cache_all_tracebacks", "_cache_all_frames")
  186. def __init__(
  187. self,
  188. exc: BaseException,
  189. te: traceback.TracebackException | None = None,
  190. *,
  191. skip: int = 0,
  192. hide: bool = True,
  193. ) -> None:
  194. self._te = _process_traceback(exc, te, skip=skip, hide=hide)
  195. def __str__(self) -> str:
  196. return f"<{type(self).__name__} {self._te}>"
  197. @cached_property
  198. def all_tracebacks(
  199. self,
  200. ) -> list[tuple[str | None, traceback.TracebackException]]:
  201. out = []
  202. current = self._te
  203. while current is not None:
  204. if current.__cause__ is not None:
  205. chained_msg = (
  206. "The above exception was the direct cause of the"
  207. " following exception"
  208. )
  209. chained_exc = current.__cause__
  210. elif current.__context__ is not None and not current.__suppress_context__:
  211. chained_msg = (
  212. "During handling of the above exception, another"
  213. " exception occurred"
  214. )
  215. chained_exc = current.__context__
  216. else:
  217. chained_msg = None
  218. chained_exc = None
  219. out.append((chained_msg, current))
  220. current = chained_exc
  221. return out
  222. @cached_property
  223. def all_frames(self) -> list[DebugFrameSummary]:
  224. return [
  225. f for _, te in self.all_tracebacks for f in te.stack # type: ignore[misc]
  226. ]
  227. def render_traceback_text(self) -> str:
  228. return "".join(self._te.format())
  229. def render_traceback_html(self, include_title: bool = True) -> str:
  230. library_frames = [f.is_library for f in self.all_frames]
  231. mark_library = 0 < sum(library_frames) < len(library_frames)
  232. rows = []
  233. if not library_frames:
  234. classes = "traceback noframe-traceback"
  235. else:
  236. classes = "traceback"
  237. for msg, current in reversed(self.all_tracebacks):
  238. row_parts = []
  239. if msg is not None:
  240. row_parts.append(f'<li><div class="exc-divider">{msg}:</div>')
  241. for frame in current.stack:
  242. frame = t.cast(DebugFrameSummary, frame)
  243. info = f' title="{escape(frame.info)}"' if frame.info else ""
  244. row_parts.append(f"<li{info}>{frame.render_html(mark_library)}")
  245. rows.append("\n".join(row_parts))
  246. is_syntax_error = issubclass(self._te.exc_type, SyntaxError)
  247. if include_title:
  248. if is_syntax_error:
  249. title = "Syntax Error"
  250. else:
  251. title = "Traceback <em>(most recent call last)</em>:"
  252. else:
  253. title = ""
  254. exc_full = escape("".join(self._te.format_exception_only()))
  255. if is_syntax_error:
  256. description = f"<pre class=syntaxerror>{exc_full}</pre>"
  257. else:
  258. description = f"<blockquote>{exc_full}</blockquote>"
  259. return SUMMARY_HTML % {
  260. "classes": classes,
  261. "title": f"<h3>{title}</h3>",
  262. "frames": "\n".join(rows),
  263. "description": description,
  264. }
  265. def render_debugger_html(
  266. self, evalex: bool, secret: str, evalex_trusted: bool
  267. ) -> str:
  268. exc_lines = list(self._te.format_exception_only())
  269. plaintext = "".join(self._te.format())
  270. return PAGE_HTML % {
  271. "evalex": "true" if evalex else "false",
  272. "evalex_trusted": "true" if evalex_trusted else "false",
  273. "console": "false",
  274. "title": escape(exc_lines[0]),
  275. "exception": escape("".join(exc_lines)),
  276. "exception_type": escape(self._te.exc_type.__name__),
  277. "summary": self.render_traceback_html(include_title=False),
  278. "plaintext": escape(plaintext),
  279. "plaintext_cs": re.sub("-{2,}", "-", plaintext),
  280. "secret": secret,
  281. }
  282. class DebugFrameSummary(traceback.FrameSummary):
  283. """A :class:`traceback.FrameSummary` that can evaluate code in the
  284. frame's namespace.
  285. """
  286. __slots__ = (
  287. "local_ns",
  288. "global_ns",
  289. "_cache_info",
  290. "_cache_is_library",
  291. "_cache_console",
  292. )
  293. def __init__(
  294. self,
  295. *,
  296. locals: dict[str, t.Any],
  297. globals: dict[str, t.Any],
  298. **kwargs: t.Any,
  299. ) -> None:
  300. super().__init__(locals=None, **kwargs)
  301. self.local_ns = locals
  302. self.global_ns = globals
  303. @cached_property
  304. def info(self) -> str | None:
  305. return self.local_ns.get("__traceback_info__")
  306. @cached_property
  307. def is_library(self) -> bool:
  308. return any(
  309. self.filename.startswith((path, os.path.realpath(path)))
  310. for path in sysconfig.get_paths().values()
  311. )
  312. @cached_property
  313. def console(self) -> Console:
  314. return Console(self.global_ns, self.local_ns)
  315. def eval(self, code: str) -> t.Any:
  316. return self.console.eval(code)
  317. def render_html(self, mark_library: bool) -> str:
  318. context = 5
  319. lines = linecache.getlines(self.filename)
  320. line_idx = self.lineno - 1 # type: ignore[operator]
  321. start_idx = max(0, line_idx - context)
  322. stop_idx = min(len(lines), line_idx + context + 1)
  323. rendered_lines = []
  324. def render_line(line: str, cls: str) -> None:
  325. line = line.expandtabs().rstrip()
  326. stripped_line = line.strip()
  327. prefix = len(line) - len(stripped_line)
  328. colno = getattr(self, "colno", 0)
  329. end_colno = getattr(self, "end_colno", 0)
  330. if cls == "current" and colno and end_colno:
  331. arrow = (
  332. f'\n<span class="ws">{" " * prefix}</span>'
  333. f'{" " * (colno - prefix)}{"^" * (end_colno - colno)}'
  334. )
  335. else:
  336. arrow = ""
  337. rendered_lines.append(
  338. f'<pre class="line {cls}"><span class="ws">{" " * prefix}</span>'
  339. f"{escape(stripped_line) if stripped_line else ' '}"
  340. f"{arrow if arrow else ''}</pre>"
  341. )
  342. if lines:
  343. for line in lines[start_idx:line_idx]:
  344. render_line(line, "before")
  345. render_line(lines[line_idx], "current")
  346. for line in lines[line_idx + 1 : stop_idx]:
  347. render_line(line, "after")
  348. return FRAME_HTML % {
  349. "id": id(self),
  350. "filename": escape(self.filename),
  351. "lineno": self.lineno,
  352. "function_name": escape(self.name),
  353. "lines": "\n".join(rendered_lines),
  354. "library": "library" if mark_library and self.is_library else "",
  355. }
  356. def render_console_html(secret: str, evalex_trusted: bool) -> str:
  357. return CONSOLE_HTML % {
  358. "evalex": "true",
  359. "evalex_trusted": "true" if evalex_trusted else "false",
  360. "console": "true",
  361. "title": "Console",
  362. "secret": secret,
  363. }