showexceptions.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. require 'ostruct'
  2. require 'erb'
  3. require 'rack/request'
  4. require 'rack/utils'
  5. module Rack
  6. # Rack::ShowExceptions catches all exceptions raised from the app it
  7. # wraps. It shows a useful backtrace with the sourcefile and
  8. # clickable context, the whole Rack environment and the request
  9. # data.
  10. #
  11. # Be careful when you use this on public-facing sites as it could
  12. # reveal information helpful to attackers.
  13. class ShowExceptions
  14. CONTEXT = 7
  15. def initialize(app)
  16. @app = app
  17. @template = ERB.new(TEMPLATE)
  18. end
  19. def call(env)
  20. @app.call(env)
  21. rescue StandardError, LoadError, SyntaxError => e
  22. exception_string = dump_exception(e)
  23. env["rack.errors"].puts(exception_string)
  24. env["rack.errors"].flush
  25. if prefers_plain_text?(env)
  26. content_type = "text/plain"
  27. body = [exception_string]
  28. else
  29. content_type = "text/html"
  30. body = pretty(env, e)
  31. end
  32. [500,
  33. {"Content-Type" => content_type,
  34. "Content-Length" => Rack::Utils.bytesize(body.join).to_s},
  35. body]
  36. end
  37. def prefers_plain_text?(env)
  38. env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" && (!env["HTTP_ACCEPT"] || !env["HTTP_ACCEPT"].include?("text/html"))
  39. end
  40. def dump_exception(exception)
  41. string = "#{exception.class}: #{exception.message}\n"
  42. string << exception.backtrace.map { |l| "\t#{l}" }.join("\n")
  43. string
  44. end
  45. def pretty(env, exception)
  46. req = Rack::Request.new(env)
  47. # This double assignment is to prevent an "unused variable" warning on
  48. # Ruby 1.9.3. Yes, it is dumb, but I don't like Ruby yelling at me.
  49. path = path = (req.script_name + req.path_info).squeeze("/")
  50. # This double assignment is to prevent an "unused variable" warning on
  51. # Ruby 1.9.3. Yes, it is dumb, but I don't like Ruby yelling at me.
  52. frames = frames = exception.backtrace.map { |line|
  53. frame = OpenStruct.new
  54. if line =~ /(.*?):(\d+)(:in `(.*)')?/
  55. frame.filename = $1
  56. frame.lineno = $2.to_i
  57. frame.function = $4
  58. begin
  59. lineno = frame.lineno-1
  60. lines = ::File.readlines(frame.filename)
  61. frame.pre_context_lineno = [lineno-CONTEXT, 0].max
  62. frame.pre_context = lines[frame.pre_context_lineno...lineno]
  63. frame.context_line = lines[lineno].chomp
  64. frame.post_context_lineno = [lineno+CONTEXT, lines.size].min
  65. frame.post_context = lines[lineno+1..frame.post_context_lineno]
  66. rescue
  67. end
  68. frame
  69. else
  70. nil
  71. end
  72. }.compact
  73. [@template.result(binding)]
  74. end
  75. def h(obj) # :nodoc:
  76. case obj
  77. when String
  78. Utils.escape_html(obj)
  79. else
  80. Utils.escape_html(obj.inspect)
  81. end
  82. end
  83. # :stopdoc:
  84. # adapted from Django <djangoproject.com>
  85. # Copyright (c) 2005, the Lawrence Journal-World
  86. # Used under the modified BSD license:
  87. # http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5
  88. TEMPLATE = <<'HTML'
  89. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  90. <html lang="en">
  91. <head>
  92. <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  93. <meta name="robots" content="NONE,NOARCHIVE" />
  94. <title><%=h exception.class %> at <%=h path %></title>
  95. <style type="text/css">
  96. html * { padding:0; margin:0; }
  97. body * { padding:10px 20px; }
  98. body * * { padding:0; }
  99. body { font:small sans-serif; }
  100. body>div { border-bottom:1px solid #ddd; }
  101. h1 { font-weight:normal; }
  102. h2 { margin-bottom:.8em; }
  103. h2 span { font-size:80%; color:#666; font-weight:normal; }
  104. h3 { margin:1em 0 .5em 0; }
  105. h4 { margin:0 0 .5em 0; font-weight: normal; }
  106. table {
  107. border:1px solid #ccc; border-collapse: collapse; background:white; }
  108. tbody td, tbody th { vertical-align:top; padding:2px 3px; }
  109. thead th {
  110. padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
  111. font-weight:normal; font-size:11px; border:1px solid #ddd; }
  112. tbody th { text-align:right; color:#666; padding-right:.5em; }
  113. table.vars { margin:5px 0 2px 40px; }
  114. table.vars td, table.req td { font-family:monospace; }
  115. table td.code { width:100%;}
  116. table td.code div { overflow:hidden; }
  117. table.source th { color:#666; }
  118. table.source td {
  119. font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
  120. ul.traceback { list-style-type:none; }
  121. ul.traceback li.frame { margin-bottom:1em; }
  122. div.context { margin: 10px 0; }
  123. div.context ol {
  124. padding-left:30px; margin:0 10px; list-style-position: inside; }
  125. div.context ol li {
  126. font-family:monospace; white-space:pre; color:#666; cursor:pointer; }
  127. div.context ol.context-line li { color:black; background-color:#ccc; }
  128. div.context ol.context-line li span { float: right; }
  129. div.commands { margin-left: 40px; }
  130. div.commands a { color:black; text-decoration:none; }
  131. #summary { background: #ffc; }
  132. #summary h2 { font-weight: normal; color: #666; }
  133. #summary ul#quicklinks { list-style-type: none; margin-bottom: 2em; }
  134. #summary ul#quicklinks li { float: left; padding: 0 1em; }
  135. #summary ul#quicklinks>li+li { border-left: 1px #666 solid; }
  136. #explanation { background:#eee; }
  137. #template, #template-not-exist { background:#f6f6f6; }
  138. #template-not-exist ul { margin: 0 0 0 20px; }
  139. #traceback { background:#eee; }
  140. #requestinfo { background:#f6f6f6; padding-left:120px; }
  141. #summary table { border:none; background:transparent; }
  142. #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
  143. #requestinfo h3 { margin-bottom:-1em; }
  144. .error { background: #ffc; }
  145. .specific { color:#cc3300; font-weight:bold; }
  146. </style>
  147. <script type="text/javascript">
  148. //<!--
  149. function getElementsByClassName(oElm, strTagName, strClassName){
  150. // Written by Jonathan Snook, http://www.snook.ca/jon;
  151. // Add-ons by Robert Nyman, http://www.robertnyman.com
  152. var arrElements = (strTagName == "*" && document.all)? document.all :
  153. oElm.getElementsByTagName(strTagName);
  154. var arrReturnElements = new Array();
  155. strClassName = strClassName.replace(/\-/g, "\\-");
  156. var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$$)");
  157. var oElement;
  158. for(var i=0; i<arrElements.length; i++){
  159. oElement = arrElements[i];
  160. if(oRegExp.test(oElement.className)){
  161. arrReturnElements.push(oElement);
  162. }
  163. }
  164. return (arrReturnElements)
  165. }
  166. function hideAll(elems) {
  167. for (var e = 0; e < elems.length; e++) {
  168. elems[e].style.display = 'none';
  169. }
  170. }
  171. window.onload = function() {
  172. hideAll(getElementsByClassName(document, 'table', 'vars'));
  173. hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
  174. hideAll(getElementsByClassName(document, 'ol', 'post-context'));
  175. }
  176. function toggle() {
  177. for (var i = 0; i < arguments.length; i++) {
  178. var e = document.getElementById(arguments[i]);
  179. if (e) {
  180. e.style.display = e.style.display == 'none' ? 'block' : 'none';
  181. }
  182. }
  183. return false;
  184. }
  185. function varToggle(link, id) {
  186. toggle('v' + id);
  187. var s = link.getElementsByTagName('span')[0];
  188. var uarr = String.fromCharCode(0x25b6);
  189. var darr = String.fromCharCode(0x25bc);
  190. s.innerHTML = s.innerHTML == uarr ? darr : uarr;
  191. return false;
  192. }
  193. //-->
  194. </script>
  195. </head>
  196. <body>
  197. <div id="summary">
  198. <h1><%=h exception.class %> at <%=h path %></h1>
  199. <h2><%=h exception.message %></h2>
  200. <table><tr>
  201. <th>Ruby</th>
  202. <td>
  203. <% if first = frames.first %>
  204. <code><%=h first.filename %></code>: in <code><%=h first.function %></code>, line <%=h frames.first.lineno %>
  205. <% else %>
  206. unknown location
  207. <% end %>
  208. </td>
  209. </tr><tr>
  210. <th>Web</th>
  211. <td><code><%=h req.request_method %> <%=h(req.host + path)%></code></td>
  212. </tr></table>
  213. <h3>Jump to:</h3>
  214. <ul id="quicklinks">
  215. <li><a href="#get-info">GET</a></li>
  216. <li><a href="#post-info">POST</a></li>
  217. <li><a href="#cookie-info">Cookies</a></li>
  218. <li><a href="#env-info">ENV</a></li>
  219. </ul>
  220. </div>
  221. <div id="traceback">
  222. <h2>Traceback <span>(innermost first)</span></h2>
  223. <ul class="traceback">
  224. <% frames.each { |frame| %>
  225. <li class="frame">
  226. <code><%=h frame.filename %></code>: in <code><%=h frame.function %></code>
  227. <% if frame.context_line %>
  228. <div class="context" id="c<%=h frame.object_id %>">
  229. <% if frame.pre_context %>
  230. <ol start="<%=h frame.pre_context_lineno+1 %>" class="pre-context" id="pre<%=h frame.object_id %>">
  231. <% frame.pre_context.each { |line| %>
  232. <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li>
  233. <% } %>
  234. </ol>
  235. <% end %>
  236. <ol start="<%=h frame.lineno %>" class="context-line">
  237. <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h frame.context_line %><span>...</span></li></ol>
  238. <% if frame.post_context %>
  239. <ol start='<%=h frame.lineno+1 %>' class="post-context" id="post<%=h frame.object_id %>">
  240. <% frame.post_context.each { |line| %>
  241. <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li>
  242. <% } %>
  243. </ol>
  244. <% end %>
  245. </div>
  246. <% end %>
  247. </li>
  248. <% } %>
  249. </ul>
  250. </div>
  251. <div id="requestinfo">
  252. <h2>Request information</h2>
  253. <h3 id="get-info">GET</h3>
  254. <% if req.GET and not req.GET.empty? %>
  255. <table class="req">
  256. <thead>
  257. <tr>
  258. <th>Variable</th>
  259. <th>Value</th>
  260. </tr>
  261. </thead>
  262. <tbody>
  263. <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %>
  264. <tr>
  265. <td><%=h key %></td>
  266. <td class="code"><div><%=h val.inspect %></div></td>
  267. </tr>
  268. <% } %>
  269. </tbody>
  270. </table>
  271. <% else %>
  272. <p>No GET data.</p>
  273. <% end %>
  274. <h3 id="post-info">POST</h3>
  275. <% if req.POST and not req.POST.empty? %>
  276. <table class="req">
  277. <thead>
  278. <tr>
  279. <th>Variable</th>
  280. <th>Value</th>
  281. </tr>
  282. </thead>
  283. <tbody>
  284. <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %>
  285. <tr>
  286. <td><%=h key %></td>
  287. <td class="code"><div><%=h val.inspect %></div></td>
  288. </tr>
  289. <% } %>
  290. </tbody>
  291. </table>
  292. <% else %>
  293. <p>No POST data.</p>
  294. <% end %>
  295. <h3 id="cookie-info">COOKIES</h3>
  296. <% unless req.cookies.empty? %>
  297. <table class="req">
  298. <thead>
  299. <tr>
  300. <th>Variable</th>
  301. <th>Value</th>
  302. </tr>
  303. </thead>
  304. <tbody>
  305. <% req.cookies.each { |key, val| %>
  306. <tr>
  307. <td><%=h key %></td>
  308. <td class="code"><div><%=h val.inspect %></div></td>
  309. </tr>
  310. <% } %>
  311. </tbody>
  312. </table>
  313. <% else %>
  314. <p>No cookie data.</p>
  315. <% end %>
  316. <h3 id="env-info">Rack ENV</h3>
  317. <table class="req">
  318. <thead>
  319. <tr>
  320. <th>Variable</th>
  321. <th>Value</th>
  322. </tr>
  323. </thead>
  324. <tbody>
  325. <% env.sort_by { |k, v| k.to_s }.each { |key, val| %>
  326. <tr>
  327. <td><%=h key %></td>
  328. <td class="code"><div><%=h val %></div></td>
  329. </tr>
  330. <% } %>
  331. </tbody>
  332. </table>
  333. </div>
  334. <div id="explanation">
  335. <p>
  336. You're seeing this error because you use <code>Rack::ShowExceptions</code>.
  337. </p>
  338. </div>
  339. </body>
  340. </html>
  341. HTML
  342. # :startdoc:
  343. end
  344. end