tbtools.py 12 KB

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