web.py 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2009 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """``tornado.web`` provides a simple web framework with asynchronous
  17. features that allow it to scale to large numbers of open connections,
  18. making it ideal for `long polling
  19. <http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.
  20. Here is a simple "Hello, world" example app:
  21. .. testcode::
  22. import tornado.ioloop
  23. import tornado.web
  24. class MainHandler(tornado.web.RequestHandler):
  25. def get(self):
  26. self.write("Hello, world")
  27. if __name__ == "__main__":
  28. application = tornado.web.Application([
  29. (r"/", MainHandler),
  30. ])
  31. application.listen(8888)
  32. tornado.ioloop.IOLoop.current().start()
  33. .. testoutput::
  34. :hide:
  35. See the :doc:`guide` for additional information.
  36. Thread-safety notes
  37. -------------------
  38. In general, methods on `RequestHandler` and elsewhere in Tornado are
  39. not thread-safe. In particular, methods such as
  40. `~RequestHandler.write()`, `~RequestHandler.finish()`, and
  41. `~RequestHandler.flush()` must only be called from the main thread. If
  42. you use multiple threads it is important to use `.IOLoop.add_callback`
  43. to transfer control back to the main thread before finishing the
  44. request.
  45. """
  46. from __future__ import absolute_import, division, print_function, with_statement
  47. import base64
  48. import binascii
  49. import datetime
  50. import email.utils
  51. import functools
  52. import gzip
  53. import hashlib
  54. import hmac
  55. import mimetypes
  56. import numbers
  57. import os.path
  58. import re
  59. import stat
  60. import sys
  61. import threading
  62. import time
  63. import tornado
  64. import traceback
  65. import types
  66. from io import BytesIO
  67. from tornado.concurrent import Future
  68. from tornado import escape
  69. from tornado import gen
  70. from tornado import httputil
  71. from tornado import iostream
  72. from tornado import locale
  73. from tornado.log import access_log, app_log, gen_log
  74. from tornado import stack_context
  75. from tornado import template
  76. from tornado.escape import utf8, _unicode
  77. from tornado.util import (import_object, ObjectDict, raise_exc_info,
  78. unicode_type, _websocket_mask)
  79. from tornado.httputil import split_host_and_port
  80. try:
  81. import Cookie # py2
  82. except ImportError:
  83. import http.cookies as Cookie # py3
  84. try:
  85. import urlparse # py2
  86. except ImportError:
  87. import urllib.parse as urlparse # py3
  88. try:
  89. from urllib import urlencode # py2
  90. except ImportError:
  91. from urllib.parse import urlencode # py3
  92. MIN_SUPPORTED_SIGNED_VALUE_VERSION = 1
  93. """The oldest signed value version supported by this version of Tornado.
  94. Signed values older than this version cannot be decoded.
  95. .. versionadded:: 3.2.1
  96. """
  97. MAX_SUPPORTED_SIGNED_VALUE_VERSION = 2
  98. """The newest signed value version supported by this version of Tornado.
  99. Signed values newer than this version cannot be decoded.
  100. .. versionadded:: 3.2.1
  101. """
  102. DEFAULT_SIGNED_VALUE_VERSION = 2
  103. """The signed value version produced by `.RequestHandler.create_signed_value`.
  104. May be overridden by passing a ``version`` keyword argument.
  105. .. versionadded:: 3.2.1
  106. """
  107. DEFAULT_SIGNED_VALUE_MIN_VERSION = 1
  108. """The oldest signed value accepted by `.RequestHandler.get_secure_cookie`.
  109. May be overridden by passing a ``min_version`` keyword argument.
  110. .. versionadded:: 3.2.1
  111. """
  112. class RequestHandler(object):
  113. """Base class for HTTP request handlers.
  114. Subclasses must define at least one of the methods defined in the
  115. "Entry points" section below.
  116. """
  117. SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
  118. "OPTIONS")
  119. _template_loaders = {} # {path: template.BaseLoader}
  120. _template_loader_lock = threading.Lock()
  121. _remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]")
  122. def __init__(self, application, request, **kwargs):
  123. super(RequestHandler, self).__init__()
  124. self.application = application
  125. self.request = request
  126. self._headers_written = False
  127. self._finished = False
  128. self._auto_finish = True
  129. self._transforms = None # will be set in _execute
  130. self._prepared_future = None
  131. self.path_args = None
  132. self.path_kwargs = None
  133. self.ui = ObjectDict((n, self._ui_method(m)) for n, m in
  134. application.ui_methods.items())
  135. # UIModules are available as both `modules` and `_tt_modules` in the
  136. # template namespace. Historically only `modules` was available
  137. # but could be clobbered by user additions to the namespace.
  138. # The template {% module %} directive looks in `_tt_modules` to avoid
  139. # possible conflicts.
  140. self.ui["_tt_modules"] = _UIModuleNamespace(self,
  141. application.ui_modules)
  142. self.ui["modules"] = self.ui["_tt_modules"]
  143. self.clear()
  144. self.request.connection.set_close_callback(self.on_connection_close)
  145. self.initialize(**kwargs)
  146. def initialize(self):
  147. """Hook for subclass initialization.
  148. A dictionary passed as the third argument of a url spec will be
  149. supplied as keyword arguments to initialize().
  150. Example::
  151. class ProfileHandler(RequestHandler):
  152. def initialize(self, database):
  153. self.database = database
  154. def get(self, username):
  155. ...
  156. app = Application([
  157. (r'/user/(.*)', ProfileHandler, dict(database=database)),
  158. ])
  159. """
  160. pass
  161. @property
  162. def settings(self):
  163. """An alias for `self.application.settings <Application.settings>`."""
  164. return self.application.settings
  165. def head(self, *args, **kwargs):
  166. raise HTTPError(405)
  167. def get(self, *args, **kwargs):
  168. raise HTTPError(405)
  169. def post(self, *args, **kwargs):
  170. raise HTTPError(405)
  171. def delete(self, *args, **kwargs):
  172. raise HTTPError(405)
  173. def patch(self, *args, **kwargs):
  174. raise HTTPError(405)
  175. def put(self, *args, **kwargs):
  176. raise HTTPError(405)
  177. def options(self, *args, **kwargs):
  178. raise HTTPError(405)
  179. def prepare(self):
  180. """Called at the beginning of a request before `get`/`post`/etc.
  181. Override this method to perform common initialization regardless
  182. of the request method.
  183. Asynchronous support: Decorate this method with `.gen.coroutine`
  184. or `.return_future` to make it asynchronous (the
  185. `asynchronous` decorator cannot be used on `prepare`).
  186. If this method returns a `.Future` execution will not proceed
  187. until the `.Future` is done.
  188. .. versionadded:: 3.1
  189. Asynchronous support.
  190. """
  191. pass
  192. def on_finish(self):
  193. """Called after the end of a request.
  194. Override this method to perform cleanup, logging, etc.
  195. This method is a counterpart to `prepare`. ``on_finish`` may
  196. not produce any output, as it is called after the response
  197. has been sent to the client.
  198. """
  199. pass
  200. def on_connection_close(self):
  201. """Called in async handlers if the client closed the connection.
  202. Override this to clean up resources associated with
  203. long-lived connections. Note that this method is called only if
  204. the connection was closed during asynchronous processing; if you
  205. need to do cleanup after every request override `on_finish`
  206. instead.
  207. Proxies may keep a connection open for a time (perhaps
  208. indefinitely) after the client has gone away, so this method
  209. may not be called promptly after the end user closes their
  210. connection.
  211. """
  212. if _has_stream_request_body(self.__class__):
  213. if not self.request.body.done():
  214. self.request.body.set_exception(iostream.StreamClosedError())
  215. self.request.body.exception()
  216. def clear(self):
  217. """Resets all headers and content for this response."""
  218. self._headers = httputil.HTTPHeaders({
  219. "Server": "TornadoServer/%s" % tornado.version,
  220. "Content-Type": "text/html; charset=UTF-8",
  221. "Date": httputil.format_timestamp(time.time()),
  222. })
  223. self.set_default_headers()
  224. self._write_buffer = []
  225. self._status_code = 200
  226. self._reason = httputil.responses[200]
  227. def set_default_headers(self):
  228. """Override this to set HTTP headers at the beginning of the request.
  229. For example, this is the place to set a custom ``Server`` header.
  230. Note that setting such headers in the normal flow of request
  231. processing may not do what you want, since headers may be reset
  232. during error handling.
  233. """
  234. pass
  235. def set_status(self, status_code, reason=None):
  236. """Sets the status code for our response.
  237. :arg int status_code: Response status code. If ``reason`` is ``None``,
  238. it must be present in `httplib.responses <http.client.responses>`.
  239. :arg string reason: Human-readable reason phrase describing the status
  240. code. If ``None``, it will be filled in from
  241. `httplib.responses <http.client.responses>`.
  242. """
  243. self._status_code = status_code
  244. if reason is not None:
  245. self._reason = escape.native_str(reason)
  246. else:
  247. try:
  248. self._reason = httputil.responses[status_code]
  249. except KeyError:
  250. raise ValueError("unknown status code %d", status_code)
  251. def get_status(self):
  252. """Returns the status code for our response."""
  253. return self._status_code
  254. def set_header(self, name, value):
  255. """Sets the given response header name and value.
  256. If a datetime is given, we automatically format it according to the
  257. HTTP specification. If the value is not a string, we convert it to
  258. a string. All header values are then encoded as UTF-8.
  259. """
  260. self._headers[name] = self._convert_header_value(value)
  261. def add_header(self, name, value):
  262. """Adds the given response header and value.
  263. Unlike `set_header`, `add_header` may be called multiple times
  264. to return multiple values for the same header.
  265. """
  266. self._headers.add(name, self._convert_header_value(value))
  267. def clear_header(self, name):
  268. """Clears an outgoing header, undoing a previous `set_header` call.
  269. Note that this method does not apply to multi-valued headers
  270. set by `add_header`.
  271. """
  272. if name in self._headers:
  273. del self._headers[name]
  274. _INVALID_HEADER_CHAR_RE = re.compile(br"[\x00-\x1f]")
  275. def _convert_header_value(self, value):
  276. if isinstance(value, bytes):
  277. pass
  278. elif isinstance(value, unicode_type):
  279. value = value.encode('utf-8')
  280. elif isinstance(value, numbers.Integral):
  281. # return immediately since we know the converted value will be safe
  282. return str(value)
  283. elif isinstance(value, datetime.datetime):
  284. return httputil.format_timestamp(value)
  285. else:
  286. raise TypeError("Unsupported header value %r" % value)
  287. # If \n is allowed into the header, it is possible to inject
  288. # additional headers or split the request.
  289. if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
  290. raise ValueError("Unsafe header value %r", value)
  291. return value
  292. _ARG_DEFAULT = []
  293. def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
  294. """Returns the value of the argument with the given name.
  295. If default is not provided, the argument is considered to be
  296. required, and we raise a `MissingArgumentError` if it is missing.
  297. If the argument appears in the url more than once, we return the
  298. last value.
  299. The returned value is always unicode.
  300. """
  301. return self._get_argument(name, default, self.request.arguments, strip)
  302. def get_arguments(self, name, strip=True):
  303. """Returns a list of the arguments with the given name.
  304. If the argument is not present, returns an empty list.
  305. The returned values are always unicode.
  306. """
  307. # Make sure `get_arguments` isn't accidentally being called with a
  308. # positional argument that's assumed to be a default (like in
  309. # `get_argument`.)
  310. assert isinstance(strip, bool)
  311. return self._get_arguments(name, self.request.arguments, strip)
  312. def get_body_argument(self, name, default=_ARG_DEFAULT, strip=True):
  313. """Returns the value of the argument with the given name
  314. from the request body.
  315. If default is not provided, the argument is considered to be
  316. required, and we raise a `MissingArgumentError` if it is missing.
  317. If the argument appears in the url more than once, we return the
  318. last value.
  319. The returned value is always unicode.
  320. .. versionadded:: 3.2
  321. """
  322. return self._get_argument(name, default, self.request.body_arguments,
  323. strip)
  324. def get_body_arguments(self, name, strip=True):
  325. """Returns a list of the body arguments with the given name.
  326. If the argument is not present, returns an empty list.
  327. The returned values are always unicode.
  328. .. versionadded:: 3.2
  329. """
  330. return self._get_arguments(name, self.request.body_arguments, strip)
  331. def get_query_argument(self, name, default=_ARG_DEFAULT, strip=True):
  332. """Returns the value of the argument with the given name
  333. from the request query string.
  334. If default is not provided, the argument is considered to be
  335. required, and we raise a `MissingArgumentError` if it is missing.
  336. If the argument appears in the url more than once, we return the
  337. last value.
  338. The returned value is always unicode.
  339. .. versionadded:: 3.2
  340. """
  341. return self._get_argument(name, default,
  342. self.request.query_arguments, strip)
  343. def get_query_arguments(self, name, strip=True):
  344. """Returns a list of the query arguments with the given name.
  345. If the argument is not present, returns an empty list.
  346. The returned values are always unicode.
  347. .. versionadded:: 3.2
  348. """
  349. return self._get_arguments(name, self.request.query_arguments, strip)
  350. def _get_argument(self, name, default, source, strip=True):
  351. args = self._get_arguments(name, source, strip=strip)
  352. if not args:
  353. if default is self._ARG_DEFAULT:
  354. raise MissingArgumentError(name)
  355. return default
  356. return args[-1]
  357. def _get_arguments(self, name, source, strip=True):
  358. values = []
  359. for v in source.get(name, []):
  360. v = self.decode_argument(v, name=name)
  361. if isinstance(v, unicode_type):
  362. # Get rid of any weird control chars (unless decoding gave
  363. # us bytes, in which case leave it alone)
  364. v = RequestHandler._remove_control_chars_regex.sub(" ", v)
  365. if strip:
  366. v = v.strip()
  367. values.append(v)
  368. return values
  369. def decode_argument(self, value, name=None):
  370. """Decodes an argument from the request.
  371. The argument has been percent-decoded and is now a byte string.
  372. By default, this method decodes the argument as utf-8 and returns
  373. a unicode string, but this may be overridden in subclasses.
  374. This method is used as a filter for both `get_argument()` and for
  375. values extracted from the url and passed to `get()`/`post()`/etc.
  376. The name of the argument is provided if known, but may be None
  377. (e.g. for unnamed groups in the url regex).
  378. """
  379. try:
  380. return _unicode(value)
  381. except UnicodeDecodeError:
  382. raise HTTPError(400, "Invalid unicode in %s: %r" %
  383. (name or "url", value[:40]))
  384. @property
  385. def cookies(self):
  386. """An alias for
  387. `self.request.cookies <.httputil.HTTPServerRequest.cookies>`."""
  388. return self.request.cookies
  389. def get_cookie(self, name, default=None):
  390. """Gets the value of the cookie with the given name, else default."""
  391. if self.request.cookies is not None and name in self.request.cookies:
  392. return self.request.cookies[name].value
  393. return default
  394. def set_cookie(self, name, value, domain=None, expires=None, path="/",
  395. expires_days=None, **kwargs):
  396. """Sets the given cookie name/value with the given options.
  397. Additional keyword arguments are set on the Cookie.Morsel
  398. directly.
  399. See http://docs.python.org/library/cookie.html#morsel-objects
  400. for available attributes.
  401. """
  402. # The cookie library only accepts type str, in both python 2 and 3
  403. name = escape.native_str(name)
  404. value = escape.native_str(value)
  405. if re.search(r"[\x00-\x20]", name + value):
  406. # Don't let us accidentally inject bad stuff
  407. raise ValueError("Invalid cookie %r: %r" % (name, value))
  408. if not hasattr(self, "_new_cookie"):
  409. self._new_cookie = Cookie.SimpleCookie()
  410. if name in self._new_cookie:
  411. del self._new_cookie[name]
  412. self._new_cookie[name] = value
  413. morsel = self._new_cookie[name]
  414. if domain:
  415. morsel["domain"] = domain
  416. if expires_days is not None and not expires:
  417. expires = datetime.datetime.utcnow() + datetime.timedelta(
  418. days=expires_days)
  419. if expires:
  420. morsel["expires"] = httputil.format_timestamp(expires)
  421. if path:
  422. morsel["path"] = path
  423. for k, v in kwargs.items():
  424. if k == 'max_age':
  425. k = 'max-age'
  426. # skip falsy values for httponly and secure flags because
  427. # SimpleCookie sets them regardless
  428. if k in ['httponly', 'secure'] and not v:
  429. continue
  430. morsel[k] = v
  431. def clear_cookie(self, name, path="/", domain=None):
  432. """Deletes the cookie with the given name.
  433. Due to limitations of the cookie protocol, you must pass the same
  434. path and domain to clear a cookie as were used when that cookie
  435. was set (but there is no way to find out on the server side
  436. which values were used for a given cookie).
  437. """
  438. expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
  439. self.set_cookie(name, value="", path=path, expires=expires,
  440. domain=domain)
  441. def clear_all_cookies(self, path="/", domain=None):
  442. """Deletes all the cookies the user sent with this request.
  443. See `clear_cookie` for more information on the path and domain
  444. parameters.
  445. .. versionchanged:: 3.2
  446. Added the ``path`` and ``domain`` parameters.
  447. """
  448. for name in self.request.cookies:
  449. self.clear_cookie(name, path=path, domain=domain)
  450. def set_secure_cookie(self, name, value, expires_days=30, version=None,
  451. **kwargs):
  452. """Signs and timestamps a cookie so it cannot be forged.
  453. You must specify the ``cookie_secret`` setting in your Application
  454. to use this method. It should be a long, random sequence of bytes
  455. to be used as the HMAC secret for the signature.
  456. To read a cookie set with this method, use `get_secure_cookie()`.
  457. Note that the ``expires_days`` parameter sets the lifetime of the
  458. cookie in the browser, but is independent of the ``max_age_days``
  459. parameter to `get_secure_cookie`.
  460. Secure cookies may contain arbitrary byte values, not just unicode
  461. strings (unlike regular cookies)
  462. .. versionchanged:: 3.2.1
  463. Added the ``version`` argument. Introduced cookie version 2
  464. and made it the default.
  465. """
  466. self.set_cookie(name, self.create_signed_value(name, value,
  467. version=version),
  468. expires_days=expires_days, **kwargs)
  469. def create_signed_value(self, name, value, version=None):
  470. """Signs and timestamps a string so it cannot be forged.
  471. Normally used via set_secure_cookie, but provided as a separate
  472. method for non-cookie uses. To decode a value not stored
  473. as a cookie use the optional value argument to get_secure_cookie.
  474. .. versionchanged:: 3.2.1
  475. Added the ``version`` argument. Introduced cookie version 2
  476. and made it the default.
  477. """
  478. self.require_setting("cookie_secret", "secure cookies")
  479. secret = self.application.settings["cookie_secret"]
  480. key_version = None
  481. if isinstance(secret, dict):
  482. if self.application.settings.get("key_version") is None:
  483. raise Exception("key_version setting must be used for secret_key dicts")
  484. key_version = self.application.settings["key_version"]
  485. return create_signed_value(secret, name, value, version=version,
  486. key_version=key_version)
  487. def get_secure_cookie(self, name, value=None, max_age_days=31,
  488. min_version=None):
  489. """Returns the given signed cookie if it validates, or None.
  490. The decoded cookie value is returned as a byte string (unlike
  491. `get_cookie`).
  492. .. versionchanged:: 3.2.1
  493. Added the ``min_version`` argument. Introduced cookie version 2;
  494. both versions 1 and 2 are accepted by default.
  495. """
  496. self.require_setting("cookie_secret", "secure cookies")
  497. if value is None:
  498. value = self.get_cookie(name)
  499. return decode_signed_value(self.application.settings["cookie_secret"],
  500. name, value, max_age_days=max_age_days,
  501. min_version=min_version)
  502. def get_secure_cookie_key_version(self, name, value=None):
  503. """Returns the signing key version of the secure cookie.
  504. The version is returned as int.
  505. """
  506. self.require_setting("cookie_secret", "secure cookies")
  507. if value is None:
  508. value = self.get_cookie(name)
  509. return get_signature_key_version(value)
  510. def redirect(self, url, permanent=False, status=None):
  511. """Sends a redirect to the given (optionally relative) URL.
  512. If the ``status`` argument is specified, that value is used as the
  513. HTTP status code; otherwise either 301 (permanent) or 302
  514. (temporary) is chosen based on the ``permanent`` argument.
  515. The default is 302 (temporary).
  516. """
  517. if self._headers_written:
  518. raise Exception("Cannot redirect after headers have been written")
  519. if status is None:
  520. status = 301 if permanent else 302
  521. else:
  522. assert isinstance(status, int) and 300 <= status <= 399
  523. self.set_status(status)
  524. self.set_header("Location", utf8(url))
  525. self.finish()
  526. def write(self, chunk):
  527. """Writes the given chunk to the output buffer.
  528. To write the output to the network, use the flush() method below.
  529. If the given chunk is a dictionary, we write it as JSON and set
  530. the Content-Type of the response to be ``application/json``.
  531. (if you want to send JSON as a different ``Content-Type``, call
  532. set_header *after* calling write()).
  533. Note that lists are not converted to JSON because of a potential
  534. cross-site security vulnerability. All JSON output should be
  535. wrapped in a dictionary. More details at
  536. http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and
  537. https://github.com/facebook/tornado/issues/1009
  538. """
  539. if self._finished:
  540. raise RuntimeError("Cannot write() after finish()")
  541. if not isinstance(chunk, (bytes, unicode_type, dict)):
  542. message = "write() only accepts bytes, unicode, and dict objects"
  543. if isinstance(chunk, list):
  544. message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
  545. raise TypeError(message)
  546. if isinstance(chunk, dict):
  547. chunk = escape.json_encode(chunk)
  548. self.set_header("Content-Type", "application/json; charset=UTF-8")
  549. chunk = utf8(chunk)
  550. self._write_buffer.append(chunk)
  551. def render(self, template_name, **kwargs):
  552. """Renders the template with the given arguments as the response."""
  553. html = self.render_string(template_name, **kwargs)
  554. # Insert the additional JS and CSS added by the modules on the page
  555. js_embed = []
  556. js_files = []
  557. css_embed = []
  558. css_files = []
  559. html_heads = []
  560. html_bodies = []
  561. for module in getattr(self, "_active_modules", {}).values():
  562. embed_part = module.embedded_javascript()
  563. if embed_part:
  564. js_embed.append(utf8(embed_part))
  565. file_part = module.javascript_files()
  566. if file_part:
  567. if isinstance(file_part, (unicode_type, bytes)):
  568. js_files.append(file_part)
  569. else:
  570. js_files.extend(file_part)
  571. embed_part = module.embedded_css()
  572. if embed_part:
  573. css_embed.append(utf8(embed_part))
  574. file_part = module.css_files()
  575. if file_part:
  576. if isinstance(file_part, (unicode_type, bytes)):
  577. css_files.append(file_part)
  578. else:
  579. css_files.extend(file_part)
  580. head_part = module.html_head()
  581. if head_part:
  582. html_heads.append(utf8(head_part))
  583. body_part = module.html_body()
  584. if body_part:
  585. html_bodies.append(utf8(body_part))
  586. def is_absolute(path):
  587. return any(path.startswith(x) for x in ["/", "http:", "https:"])
  588. if js_files:
  589. # Maintain order of JavaScript files given by modules
  590. paths = []
  591. unique_paths = set()
  592. for path in js_files:
  593. if not is_absolute(path):
  594. path = self.static_url(path)
  595. if path not in unique_paths:
  596. paths.append(path)
  597. unique_paths.add(path)
  598. js = ''.join('<script src="' + escape.xhtml_escape(p) +
  599. '" type="text/javascript"></script>'
  600. for p in paths)
  601. sloc = html.rindex(b'</body>')
  602. html = html[:sloc] + utf8(js) + b'\n' + html[sloc:]
  603. if js_embed:
  604. js = b'<script type="text/javascript">\n//<![CDATA[\n' + \
  605. b'\n'.join(js_embed) + b'\n//]]>\n</script>'
  606. sloc = html.rindex(b'</body>')
  607. html = html[:sloc] + js + b'\n' + html[sloc:]
  608. if css_files:
  609. paths = []
  610. unique_paths = set()
  611. for path in css_files:
  612. if not is_absolute(path):
  613. path = self.static_url(path)
  614. if path not in unique_paths:
  615. paths.append(path)
  616. unique_paths.add(path)
  617. css = ''.join('<link href="' + escape.xhtml_escape(p) + '" '
  618. 'type="text/css" rel="stylesheet"/>'
  619. for p in paths)
  620. hloc = html.index(b'</head>')
  621. html = html[:hloc] + utf8(css) + b'\n' + html[hloc:]
  622. if css_embed:
  623. css = b'<style type="text/css">\n' + b'\n'.join(css_embed) + \
  624. b'\n</style>'
  625. hloc = html.index(b'</head>')
  626. html = html[:hloc] + css + b'\n' + html[hloc:]
  627. if html_heads:
  628. hloc = html.index(b'</head>')
  629. html = html[:hloc] + b''.join(html_heads) + b'\n' + html[hloc:]
  630. if html_bodies:
  631. hloc = html.index(b'</body>')
  632. html = html[:hloc] + b''.join(html_bodies) + b'\n' + html[hloc:]
  633. self.finish(html)
  634. def render_string(self, template_name, **kwargs):
  635. """Generate the given template with the given arguments.
  636. We return the generated byte string (in utf8). To generate and
  637. write a template as a response, use render() above.
  638. """
  639. # If no template_path is specified, use the path of the calling file
  640. template_path = self.get_template_path()
  641. if not template_path:
  642. frame = sys._getframe(0)
  643. web_file = frame.f_code.co_filename
  644. while frame.f_code.co_filename == web_file:
  645. frame = frame.f_back
  646. template_path = os.path.dirname(frame.f_code.co_filename)
  647. with RequestHandler._template_loader_lock:
  648. if template_path not in RequestHandler._template_loaders:
  649. loader = self.create_template_loader(template_path)
  650. RequestHandler._template_loaders[template_path] = loader
  651. else:
  652. loader = RequestHandler._template_loaders[template_path]
  653. t = loader.load(template_name)
  654. namespace = self.get_template_namespace()
  655. namespace.update(kwargs)
  656. return t.generate(**namespace)
  657. def get_template_namespace(self):
  658. """Returns a dictionary to be used as the default template namespace.
  659. May be overridden by subclasses to add or modify values.
  660. The results of this method will be combined with additional
  661. defaults in the `tornado.template` module and keyword arguments
  662. to `render` or `render_string`.
  663. """
  664. namespace = dict(
  665. handler=self,
  666. request=self.request,
  667. current_user=self.current_user,
  668. locale=self.locale,
  669. _=self.locale.translate,
  670. pgettext=self.locale.pgettext,
  671. static_url=self.static_url,
  672. xsrf_form_html=self.xsrf_form_html,
  673. reverse_url=self.reverse_url
  674. )
  675. namespace.update(self.ui)
  676. return namespace
  677. def create_template_loader(self, template_path):
  678. """Returns a new template loader for the given path.
  679. May be overridden by subclasses. By default returns a
  680. directory-based loader on the given path, using the
  681. ``autoescape`` and ``template_whitespace`` application
  682. settings. If a ``template_loader`` application setting is
  683. supplied, uses that instead.
  684. """
  685. settings = self.application.settings
  686. if "template_loader" in settings:
  687. return settings["template_loader"]
  688. kwargs = {}
  689. if "autoescape" in settings:
  690. # autoescape=None means "no escaping", so we have to be sure
  691. # to only pass this kwarg if the user asked for it.
  692. kwargs["autoescape"] = settings["autoescape"]
  693. if "template_whitespace" in settings:
  694. kwargs["whitespace"] = settings["template_whitespace"]
  695. return template.Loader(template_path, **kwargs)
  696. def flush(self, include_footers=False, callback=None):
  697. """Flushes the current output buffer to the network.
  698. The ``callback`` argument, if given, can be used for flow control:
  699. it will be run when all flushed data has been written to the socket.
  700. Note that only one flush callback can be outstanding at a time;
  701. if another flush occurs before the previous flush's callback
  702. has been run, the previous callback will be discarded.
  703. .. versionchanged:: 4.0
  704. Now returns a `.Future` if no callback is given.
  705. """
  706. chunk = b"".join(self._write_buffer)
  707. self._write_buffer = []
  708. if not self._headers_written:
  709. self._headers_written = True
  710. for transform in self._transforms:
  711. self._status_code, self._headers, chunk = \
  712. transform.transform_first_chunk(
  713. self._status_code, self._headers,
  714. chunk, include_footers)
  715. # Ignore the chunk and only write the headers for HEAD requests
  716. if self.request.method == "HEAD":
  717. chunk = None
  718. # Finalize the cookie headers (which have been stored in a side
  719. # object so an outgoing cookie could be overwritten before it
  720. # is sent).
  721. if hasattr(self, "_new_cookie"):
  722. for cookie in self._new_cookie.values():
  723. self.add_header("Set-Cookie", cookie.OutputString(None))
  724. start_line = httputil.ResponseStartLine('',
  725. self._status_code,
  726. self._reason)
  727. return self.request.connection.write_headers(
  728. start_line, self._headers, chunk, callback=callback)
  729. else:
  730. for transform in self._transforms:
  731. chunk = transform.transform_chunk(chunk, include_footers)
  732. # Ignore the chunk and only write the headers for HEAD requests
  733. if self.request.method != "HEAD":
  734. return self.request.connection.write(chunk, callback=callback)
  735. else:
  736. future = Future()
  737. future.set_result(None)
  738. return future
  739. def finish(self, chunk=None):
  740. """Finishes this response, ending the HTTP request."""
  741. if self._finished:
  742. raise RuntimeError("finish() called twice")
  743. if chunk is not None:
  744. self.write(chunk)
  745. # Automatically support ETags and add the Content-Length header if
  746. # we have not flushed any content yet.
  747. if not self._headers_written:
  748. if (self._status_code == 200 and
  749. self.request.method in ("GET", "HEAD") and
  750. "Etag" not in self._headers):
  751. self.set_etag_header()
  752. if self.check_etag_header():
  753. self._write_buffer = []
  754. self.set_status(304)
  755. if self._status_code == 304:
  756. assert not self._write_buffer, "Cannot send body with 304"
  757. self._clear_headers_for_304()
  758. elif "Content-Length" not in self._headers:
  759. content_length = sum(len(part) for part in self._write_buffer)
  760. self.set_header("Content-Length", content_length)
  761. if hasattr(self.request, "connection"):
  762. # Now that the request is finished, clear the callback we
  763. # set on the HTTPConnection (which would otherwise prevent the
  764. # garbage collection of the RequestHandler when there
  765. # are keepalive connections)
  766. self.request.connection.set_close_callback(None)
  767. self.flush(include_footers=True)
  768. self.request.finish()
  769. self._log()
  770. self._finished = True
  771. self.on_finish()
  772. # Break up a reference cycle between this handler and the
  773. # _ui_module closures to allow for faster GC on CPython.
  774. self.ui = None
  775. def send_error(self, status_code=500, **kwargs):
  776. """Sends the given HTTP error code to the browser.
  777. If `flush()` has already been called, it is not possible to send
  778. an error, so this method will simply terminate the response.
  779. If output has been written but not yet flushed, it will be discarded
  780. and replaced with the error page.
  781. Override `write_error()` to customize the error page that is returned.
  782. Additional keyword arguments are passed through to `write_error`.
  783. """
  784. if self._headers_written:
  785. gen_log.error("Cannot send error response after headers written")
  786. if not self._finished:
  787. # If we get an error between writing headers and finishing,
  788. # we are unlikely to be able to finish due to a
  789. # Content-Length mismatch. Try anyway to release the
  790. # socket.
  791. try:
  792. self.finish()
  793. except Exception:
  794. gen_log.error("Failed to flush partial response",
  795. exc_info=True)
  796. return
  797. self.clear()
  798. reason = kwargs.get('reason')
  799. if 'exc_info' in kwargs:
  800. exception = kwargs['exc_info'][1]
  801. if isinstance(exception, HTTPError) and exception.reason:
  802. reason = exception.reason
  803. self.set_status(status_code, reason=reason)
  804. try:
  805. self.write_error(status_code, **kwargs)
  806. except Exception:
  807. app_log.error("Uncaught exception in write_error", exc_info=True)
  808. if not self._finished:
  809. self.finish()
  810. def write_error(self, status_code, **kwargs):
  811. """Override to implement custom error pages.
  812. ``write_error`` may call `write`, `render`, `set_header`, etc
  813. to produce output as usual.
  814. If this error was caused by an uncaught exception (including
  815. HTTPError), an ``exc_info`` triple will be available as
  816. ``kwargs["exc_info"]``. Note that this exception may not be
  817. the "current" exception for purposes of methods like
  818. ``sys.exc_info()`` or ``traceback.format_exc``.
  819. """
  820. if self.settings.get("serve_traceback") and "exc_info" in kwargs:
  821. # in debug mode, try to send a traceback
  822. self.set_header('Content-Type', 'text/plain')
  823. for line in traceback.format_exception(*kwargs["exc_info"]):
  824. self.write(line)
  825. self.finish()
  826. else:
  827. self.finish("<html><title>%(code)d: %(message)s</title>"
  828. "<body>%(code)d: %(message)s</body></html>" % {
  829. "code": status_code,
  830. "message": self._reason,
  831. })
  832. @property
  833. def locale(self):
  834. """The locale for the current session.
  835. Determined by either `get_user_locale`, which you can override to
  836. set the locale based on, e.g., a user preference stored in a
  837. database, or `get_browser_locale`, which uses the ``Accept-Language``
  838. header.
  839. .. versionchanged: 4.1
  840. Added a property setter.
  841. """
  842. if not hasattr(self, "_locale"):
  843. self._locale = self.get_user_locale()
  844. if not self._locale:
  845. self._locale = self.get_browser_locale()
  846. assert self._locale
  847. return self._locale
  848. @locale.setter
  849. def locale(self, value):
  850. self._locale = value
  851. def get_user_locale(self):
  852. """Override to determine the locale from the authenticated user.
  853. If None is returned, we fall back to `get_browser_locale()`.
  854. This method should return a `tornado.locale.Locale` object,
  855. most likely obtained via a call like ``tornado.locale.get("en")``
  856. """
  857. return None
  858. def get_browser_locale(self, default="en_US"):
  859. """Determines the user's locale from ``Accept-Language`` header.
  860. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  861. """
  862. if "Accept-Language" in self.request.headers:
  863. languages = self.request.headers["Accept-Language"].split(",")
  864. locales = []
  865. for language in languages:
  866. parts = language.strip().split(";")
  867. if len(parts) > 1 and parts[1].startswith("q="):
  868. try:
  869. score = float(parts[1][2:])
  870. except (ValueError, TypeError):
  871. score = 0.0
  872. else:
  873. score = 1.0
  874. locales.append((parts[0], score))
  875. if locales:
  876. locales.sort(key=lambda pair: pair[1], reverse=True)
  877. codes = [l[0] for l in locales]
  878. return locale.get(*codes)
  879. return locale.get(default)
  880. @property
  881. def current_user(self):
  882. """The authenticated user for this request.
  883. This is set in one of two ways:
  884. * A subclass may override `get_current_user()`, which will be called
  885. automatically the first time ``self.current_user`` is accessed.
  886. `get_current_user()` will only be called once per request,
  887. and is cached for future access::
  888. def get_current_user(self):
  889. user_cookie = self.get_secure_cookie("user")
  890. if user_cookie:
  891. return json.loads(user_cookie)
  892. return None
  893. * It may be set as a normal variable, typically from an overridden
  894. `prepare()`::
  895. @gen.coroutine
  896. def prepare(self):
  897. user_id_cookie = self.get_secure_cookie("user_id")
  898. if user_id_cookie:
  899. self.current_user = yield load_user(user_id_cookie)
  900. Note that `prepare()` may be a coroutine while `get_current_user()`
  901. may not, so the latter form is necessary if loading the user requires
  902. asynchronous operations.
  903. The user object may any type of the application's choosing.
  904. """
  905. if not hasattr(self, "_current_user"):
  906. self._current_user = self.get_current_user()
  907. return self._current_user
  908. @current_user.setter
  909. def current_user(self, value):
  910. self._current_user = value
  911. def get_current_user(self):
  912. """Override to determine the current user from, e.g., a cookie.
  913. This method may not be a coroutine.
  914. """
  915. return None
  916. def get_login_url(self):
  917. """Override to customize the login URL based on the request.
  918. By default, we use the ``login_url`` application setting.
  919. """
  920. self.require_setting("login_url", "@tornado.web.authenticated")
  921. return self.application.settings["login_url"]
  922. def get_template_path(self):
  923. """Override to customize template path for each handler.
  924. By default, we use the ``template_path`` application setting.
  925. Return None to load templates relative to the calling file.
  926. """
  927. return self.application.settings.get("template_path")
  928. @property
  929. def xsrf_token(self):
  930. """The XSRF-prevention token for the current user/session.
  931. To prevent cross-site request forgery, we set an '_xsrf' cookie
  932. and include the same '_xsrf' value as an argument with all POST
  933. requests. If the two do not match, we reject the form submission
  934. as a potential forgery.
  935. See http://en.wikipedia.org/wiki/Cross-site_request_forgery
  936. .. versionchanged:: 3.2.2
  937. The xsrf token will now be have a random mask applied in every
  938. request, which makes it safe to include the token in pages
  939. that are compressed. See http://breachattack.com for more
  940. information on the issue fixed by this change. Old (version 1)
  941. cookies will be converted to version 2 when this method is called
  942. unless the ``xsrf_cookie_version`` `Application` setting is
  943. set to 1.
  944. .. versionchanged:: 4.3
  945. The ``xsrf_cookie_kwargs`` `Application` setting may be
  946. used to supply additional cookie options (which will be
  947. passed directly to `set_cookie`). For example,
  948. ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)``
  949. will set the ``secure`` and ``httponly`` flags on the
  950. ``_xsrf`` cookie.
  951. """
  952. if not hasattr(self, "_xsrf_token"):
  953. version, token, timestamp = self._get_raw_xsrf_token()
  954. output_version = self.settings.get("xsrf_cookie_version", 2)
  955. cookie_kwargs = self.settings.get("xsrf_cookie_kwargs", {})
  956. if output_version == 1:
  957. self._xsrf_token = binascii.b2a_hex(token)
  958. elif output_version == 2:
  959. mask = os.urandom(4)
  960. self._xsrf_token = b"|".join([
  961. b"2",
  962. binascii.b2a_hex(mask),
  963. binascii.b2a_hex(_websocket_mask(mask, token)),
  964. utf8(str(int(timestamp)))])
  965. else:
  966. raise ValueError("unknown xsrf cookie version %d",
  967. output_version)
  968. if version is None:
  969. expires_days = 30 if self.current_user else None
  970. self.set_cookie("_xsrf", self._xsrf_token,
  971. expires_days=expires_days,
  972. **cookie_kwargs)
  973. return self._xsrf_token
  974. def _get_raw_xsrf_token(self):
  975. """Read or generate the xsrf token in its raw form.
  976. The raw_xsrf_token is a tuple containing:
  977. * version: the version of the cookie from which this token was read,
  978. or None if we generated a new token in this request.
  979. * token: the raw token data; random (non-ascii) bytes.
  980. * timestamp: the time this token was generated (will not be accurate
  981. for version 1 cookies)
  982. """
  983. if not hasattr(self, '_raw_xsrf_token'):
  984. cookie = self.get_cookie("_xsrf")
  985. if cookie:
  986. version, token, timestamp = self._decode_xsrf_token(cookie)
  987. else:
  988. version, token, timestamp = None, None, None
  989. if token is None:
  990. version = None
  991. token = os.urandom(16)
  992. timestamp = time.time()
  993. self._raw_xsrf_token = (version, token, timestamp)
  994. return self._raw_xsrf_token
  995. def _decode_xsrf_token(self, cookie):
  996. """Convert a cookie string into a the tuple form returned by
  997. _get_raw_xsrf_token.
  998. """
  999. try:
  1000. m = _signed_value_version_re.match(utf8(cookie))
  1001. if m:
  1002. version = int(m.group(1))
  1003. if version == 2:
  1004. _, mask, masked_token, timestamp = cookie.split("|")
  1005. mask = binascii.a2b_hex(utf8(mask))
  1006. token = _websocket_mask(
  1007. mask, binascii.a2b_hex(utf8(masked_token)))
  1008. timestamp = int(timestamp)
  1009. return version, token, timestamp
  1010. else:
  1011. # Treat unknown versions as not present instead of failing.
  1012. raise Exception("Unknown xsrf cookie version")
  1013. else:
  1014. version = 1
  1015. try:
  1016. token = binascii.a2b_hex(utf8(cookie))
  1017. except (binascii.Error, TypeError):
  1018. token = utf8(cookie)
  1019. # We don't have a usable timestamp in older versions.
  1020. timestamp = int(time.time())
  1021. return (version, token, timestamp)
  1022. except Exception:
  1023. # Catch exceptions and return nothing instead of failing.
  1024. gen_log.debug("Uncaught exception in _decode_xsrf_token",
  1025. exc_info=True)
  1026. return None, None, None
  1027. def check_xsrf_cookie(self):
  1028. """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
  1029. To prevent cross-site request forgery, we set an ``_xsrf``
  1030. cookie and include the same value as a non-cookie
  1031. field with all ``POST`` requests. If the two do not match, we
  1032. reject the form submission as a potential forgery.
  1033. The ``_xsrf`` value may be set as either a form field named ``_xsrf``
  1034. or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
  1035. (the latter is accepted for compatibility with Django).
  1036. See http://en.wikipedia.org/wiki/Cross-site_request_forgery
  1037. Prior to release 1.1.1, this check was ignored if the HTTP header
  1038. ``X-Requested-With: XMLHTTPRequest`` was present. This exception
  1039. has been shown to be insecure and has been removed. For more
  1040. information please see
  1041. http://www.djangoproject.com/weblog/2011/feb/08/security/
  1042. http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
  1043. .. versionchanged:: 3.2.2
  1044. Added support for cookie version 2. Both versions 1 and 2 are
  1045. supported.
  1046. """
  1047. token = (self.get_argument("_xsrf", None) or
  1048. self.request.headers.get("X-Xsrftoken") or
  1049. self.request.headers.get("X-Csrftoken"))
  1050. if not token:
  1051. raise HTTPError(403, "'_xsrf' argument missing from POST")
  1052. _, token, _ = self._decode_xsrf_token(token)
  1053. _, expected_token, _ = self._get_raw_xsrf_token()
  1054. if not _time_independent_equals(utf8(token), utf8(expected_token)):
  1055. raise HTTPError(403, "XSRF cookie does not match POST argument")
  1056. def xsrf_form_html(self):
  1057. """An HTML ``<input/>`` element to be included with all POST forms.
  1058. It defines the ``_xsrf`` input value, which we check on all POST
  1059. requests to prevent cross-site request forgery. If you have set
  1060. the ``xsrf_cookies`` application setting, you must include this
  1061. HTML within all of your HTML forms.
  1062. In a template, this method should be called with ``{% module
  1063. xsrf_form_html() %}``
  1064. See `check_xsrf_cookie()` above for more information.
  1065. """
  1066. return '<input type="hidden" name="_xsrf" value="' + \
  1067. escape.xhtml_escape(self.xsrf_token) + '"/>'
  1068. def static_url(self, path, include_host=None, **kwargs):
  1069. """Returns a static URL for the given relative static file path.
  1070. This method requires you set the ``static_path`` setting in your
  1071. application (which specifies the root directory of your static
  1072. files).
  1073. This method returns a versioned url (by default appending
  1074. ``?v=<signature>``), which allows the static files to be
  1075. cached indefinitely. This can be disabled by passing
  1076. ``include_version=False`` (in the default implementation;
  1077. other static file implementations are not required to support
  1078. this, but they may support other options).
  1079. By default this method returns URLs relative to the current
  1080. host, but if ``include_host`` is true the URL returned will be
  1081. absolute. If this handler has an ``include_host`` attribute,
  1082. that value will be used as the default for all `static_url`
  1083. calls that do not pass ``include_host`` as a keyword argument.
  1084. """
  1085. self.require_setting("static_path", "static_url")
  1086. get_url = self.settings.get("static_handler_class",
  1087. StaticFileHandler).make_static_url
  1088. if include_host is None:
  1089. include_host = getattr(self, "include_host", False)
  1090. if include_host:
  1091. base = self.request.protocol + "://" + self.request.host
  1092. else:
  1093. base = ""
  1094. return base + get_url(self.settings, path, **kwargs)
  1095. def require_setting(self, name, feature="this feature"):
  1096. """Raises an exception if the given app setting is not defined."""
  1097. if not self.application.settings.get(name):
  1098. raise Exception("You must define the '%s' setting in your "
  1099. "application to use %s" % (name, feature))
  1100. def reverse_url(self, name, *args):
  1101. """Alias for `Application.reverse_url`."""
  1102. return self.application.reverse_url(name, *args)
  1103. def compute_etag(self):
  1104. """Computes the etag header to be used for this request.
  1105. By default uses a hash of the content written so far.
  1106. May be overridden to provide custom etag implementations,
  1107. or may return None to disable tornado's default etag support.
  1108. """
  1109. hasher = hashlib.sha1()
  1110. for part in self._write_buffer:
  1111. hasher.update(part)
  1112. return '"%s"' % hasher.hexdigest()
  1113. def set_etag_header(self):
  1114. """Sets the response's Etag header using ``self.compute_etag()``.
  1115. Note: no header will be set if ``compute_etag()`` returns ``None``.
  1116. This method is called automatically when the request is finished.
  1117. """
  1118. etag = self.compute_etag()
  1119. if etag is not None:
  1120. self.set_header("Etag", etag)
  1121. def check_etag_header(self):
  1122. """Checks the ``Etag`` header against requests's ``If-None-Match``.
  1123. Returns ``True`` if the request's Etag matches and a 304 should be
  1124. returned. For example::
  1125. self.set_etag_header()
  1126. if self.check_etag_header():
  1127. self.set_status(304)
  1128. return
  1129. This method is called automatically when the request is finished,
  1130. but may be called earlier for applications that override
  1131. `compute_etag` and want to do an early check for ``If-None-Match``
  1132. before completing the request. The ``Etag`` header should be set
  1133. (perhaps with `set_etag_header`) before calling this method.
  1134. """
  1135. computed_etag = utf8(self._headers.get("Etag", ""))
  1136. # Find all weak and strong etag values from If-None-Match header
  1137. # because RFC 7232 allows multiple etag values in a single header.
  1138. etags = re.findall(
  1139. br'\*|(?:W/)?"[^"]*"',
  1140. utf8(self.request.headers.get("If-None-Match", ""))
  1141. )
  1142. if not computed_etag or not etags:
  1143. return False
  1144. match = False
  1145. if etags[0] == b'*':
  1146. match = True
  1147. else:
  1148. # Use a weak comparison when comparing entity-tags.
  1149. val = lambda x: x[2:] if x.startswith(b'W/') else x
  1150. for etag in etags:
  1151. if val(etag) == val(computed_etag):
  1152. match = True
  1153. break
  1154. return match
  1155. def _stack_context_handle_exception(self, type, value, traceback):
  1156. try:
  1157. # For historical reasons _handle_request_exception only takes
  1158. # the exception value instead of the full triple,
  1159. # so re-raise the exception to ensure that it's in
  1160. # sys.exc_info()
  1161. raise_exc_info((type, value, traceback))
  1162. except Exception:
  1163. self._handle_request_exception(value)
  1164. return True
  1165. @gen.coroutine
  1166. def _execute(self, transforms, *args, **kwargs):
  1167. """Executes this request with the given output transforms."""
  1168. self._transforms = transforms
  1169. try:
  1170. if self.request.method not in self.SUPPORTED_METHODS:
  1171. raise HTTPError(405)
  1172. self.path_args = [self.decode_argument(arg) for arg in args]
  1173. self.path_kwargs = dict((k, self.decode_argument(v, name=k))
  1174. for (k, v) in kwargs.items())
  1175. # If XSRF cookies are turned on, reject form submissions without
  1176. # the proper cookie
  1177. if self.request.method not in ("GET", "HEAD", "OPTIONS") and \
  1178. self.application.settings.get("xsrf_cookies"):
  1179. self.check_xsrf_cookie()
  1180. result = self.prepare()
  1181. if result is not None:
  1182. result = yield result
  1183. if self._prepared_future is not None:
  1184. # Tell the Application we've finished with prepare()
  1185. # and are ready for the body to arrive.
  1186. self._prepared_future.set_result(None)
  1187. if self._finished:
  1188. return
  1189. if _has_stream_request_body(self.__class__):
  1190. # In streaming mode request.body is a Future that signals
  1191. # the body has been completely received. The Future has no
  1192. # result; the data has been passed to self.data_received
  1193. # instead.
  1194. try:
  1195. yield self.request.body
  1196. except iostream.StreamClosedError:
  1197. return
  1198. method = getattr(self, self.request.method.lower())
  1199. result = method(*self.path_args, **self.path_kwargs)
  1200. if result is not None:
  1201. result = yield result
  1202. if self._auto_finish and not self._finished:
  1203. self.finish()
  1204. except Exception as e:
  1205. try:
  1206. self._handle_request_exception(e)
  1207. except Exception:
  1208. app_log.error("Exception in exception handler", exc_info=True)
  1209. if (self._prepared_future is not None and
  1210. not self._prepared_future.done()):
  1211. # In case we failed before setting _prepared_future, do it
  1212. # now (to unblock the HTTP server). Note that this is not
  1213. # in a finally block to avoid GC issues prior to Python 3.4.
  1214. self._prepared_future.set_result(None)
  1215. def data_received(self, chunk):
  1216. """Implement this method to handle streamed request data.
  1217. Requires the `.stream_request_body` decorator.
  1218. """
  1219. raise NotImplementedError()
  1220. def _log(self):
  1221. """Logs the current request.
  1222. Sort of deprecated since this functionality was moved to the
  1223. Application, but left in place for the benefit of existing apps
  1224. that have overridden this method.
  1225. """
  1226. self.application.log_request(self)
  1227. def _request_summary(self):
  1228. return "%s %s (%s)" % (self.request.method, self.request.uri,
  1229. self.request.remote_ip)
  1230. def _handle_request_exception(self, e):
  1231. if isinstance(e, Finish):
  1232. # Not an error; just finish the request without logging.
  1233. if not self._finished:
  1234. self.finish(*e.args)
  1235. return
  1236. try:
  1237. self.log_exception(*sys.exc_info())
  1238. except Exception:
  1239. # An error here should still get a best-effort send_error()
  1240. # to avoid leaking the connection.
  1241. app_log.error("Error in exception logger", exc_info=True)
  1242. if self._finished:
  1243. # Extra errors after the request has been finished should
  1244. # be logged, but there is no reason to continue to try and
  1245. # send a response.
  1246. return
  1247. if isinstance(e, HTTPError):
  1248. if e.status_code not in httputil.responses and not e.reason:
  1249. gen_log.error("Bad HTTP status code: %d", e.status_code)
  1250. self.send_error(500, exc_info=sys.exc_info())
  1251. else:
  1252. self.send_error(e.status_code, exc_info=sys.exc_info())
  1253. else:
  1254. self.send_error(500, exc_info=sys.exc_info())
  1255. def log_exception(self, typ, value, tb):
  1256. """Override to customize logging of uncaught exceptions.
  1257. By default logs instances of `HTTPError` as warnings without
  1258. stack traces (on the ``tornado.general`` logger), and all
  1259. other exceptions as errors with stack traces (on the
  1260. ``tornado.application`` logger).
  1261. .. versionadded:: 3.1
  1262. """
  1263. if isinstance(value, HTTPError):
  1264. if value.log_message:
  1265. format = "%d %s: " + value.log_message
  1266. args = ([value.status_code, self._request_summary()] +
  1267. list(value.args))
  1268. gen_log.warning(format, *args)
  1269. else:
  1270. app_log.error("Uncaught exception %s\n%r", self._request_summary(),
  1271. self.request, exc_info=(typ, value, tb))
  1272. def _ui_module(self, name, module):
  1273. def render(*args, **kwargs):
  1274. if not hasattr(self, "_active_modules"):
  1275. self._active_modules = {}
  1276. if name not in self._active_modules:
  1277. self._active_modules[name] = module(self)
  1278. rendered = self._active_modules[name].render(*args, **kwargs)
  1279. return rendered
  1280. return render
  1281. def _ui_method(self, method):
  1282. return lambda *args, **kwargs: method(self, *args, **kwargs)
  1283. def _clear_headers_for_304(self):
  1284. # 304 responses should not contain entity headers (defined in
  1285. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
  1286. # not explicitly allowed by
  1287. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
  1288. headers = ["Allow", "Content-Encoding", "Content-Language",
  1289. "Content-Length", "Content-MD5", "Content-Range",
  1290. "Content-Type", "Last-Modified"]
  1291. for h in headers:
  1292. self.clear_header(h)
  1293. def asynchronous(method):
  1294. """Wrap request handler methods with this if they are asynchronous.
  1295. This decorator is for callback-style asynchronous methods; for
  1296. coroutines, use the ``@gen.coroutine`` decorator without
  1297. ``@asynchronous``. (It is legal for legacy reasons to use the two
  1298. decorators together provided ``@asynchronous`` is first, but
  1299. ``@asynchronous`` will be ignored in this case)
  1300. This decorator should only be applied to the :ref:`HTTP verb
  1301. methods <verbs>`; its behavior is undefined for any other method.
  1302. This decorator does not *make* a method asynchronous; it tells
  1303. the framework that the method *is* asynchronous. For this decorator
  1304. to be useful the method must (at least sometimes) do something
  1305. asynchronous.
  1306. If this decorator is given, the response is not finished when the
  1307. method returns. It is up to the request handler to call
  1308. `self.finish() <RequestHandler.finish>` to finish the HTTP
  1309. request. Without this decorator, the request is automatically
  1310. finished when the ``get()`` or ``post()`` method returns. Example:
  1311. .. testcode::
  1312. class MyRequestHandler(RequestHandler):
  1313. @asynchronous
  1314. def get(self):
  1315. http = httpclient.AsyncHTTPClient()
  1316. http.fetch("http://friendfeed.com/", self._on_download)
  1317. def _on_download(self, response):
  1318. self.write("Downloaded!")
  1319. self.finish()
  1320. .. testoutput::
  1321. :hide:
  1322. .. versionchanged:: 3.1
  1323. The ability to use ``@gen.coroutine`` without ``@asynchronous``.
  1324. .. versionchanged:: 4.3 Returning anything but ``None`` or a
  1325. yieldable object from a method decorated with ``@asynchronous``
  1326. is an error. Such return values were previously ignored silently.
  1327. """
  1328. # Delay the IOLoop import because it's not available on app engine.
  1329. from tornado.ioloop import IOLoop
  1330. @functools.wraps(method)
  1331. def wrapper(self, *args, **kwargs):
  1332. self._auto_finish = False
  1333. with stack_context.ExceptionStackContext(
  1334. self._stack_context_handle_exception):
  1335. result = method(self, *args, **kwargs)
  1336. if result is not None:
  1337. result = gen.convert_yielded(result)
  1338. # If @asynchronous is used with @gen.coroutine, (but
  1339. # not @gen.engine), we can automatically finish the
  1340. # request when the future resolves. Additionally,
  1341. # the Future will swallow any exceptions so we need
  1342. # to throw them back out to the stack context to finish
  1343. # the request.
  1344. def future_complete(f):
  1345. f.result()
  1346. if not self._finished:
  1347. self.finish()
  1348. IOLoop.current().add_future(result, future_complete)
  1349. # Once we have done this, hide the Future from our
  1350. # caller (i.e. RequestHandler._when_complete), which
  1351. # would otherwise set up its own callback and
  1352. # exception handler (resulting in exceptions being
  1353. # logged twice).
  1354. return None
  1355. return result
  1356. return wrapper
  1357. def stream_request_body(cls):
  1358. """Apply to `RequestHandler` subclasses to enable streaming body support.
  1359. This decorator implies the following changes:
  1360. * `.HTTPServerRequest.body` is undefined, and body arguments will not
  1361. be included in `RequestHandler.get_argument`.
  1362. * `RequestHandler.prepare` is called when the request headers have been
  1363. read instead of after the entire body has been read.
  1364. * The subclass must define a method ``data_received(self, data):``, which
  1365. will be called zero or more times as data is available. Note that
  1366. if the request has an empty body, ``data_received`` may not be called.
  1367. * ``prepare`` and ``data_received`` may return Futures (such as via
  1368. ``@gen.coroutine``, in which case the next method will not be called
  1369. until those futures have completed.
  1370. * The regular HTTP method (``post``, ``put``, etc) will be called after
  1371. the entire body has been read.
  1372. There is a subtle interaction between ``data_received`` and asynchronous
  1373. ``prepare``: The first call to ``data_received`` may occur at any point
  1374. after the call to ``prepare`` has returned *or yielded*.
  1375. """
  1376. if not issubclass(cls, RequestHandler):
  1377. raise TypeError("expected subclass of RequestHandler, got %r", cls)
  1378. cls._stream_request_body = True
  1379. return cls
  1380. def _has_stream_request_body(cls):
  1381. if not issubclass(cls, RequestHandler):
  1382. raise TypeError("expected subclass of RequestHandler, got %r", cls)
  1383. return getattr(cls, '_stream_request_body', False)
  1384. def removeslash(method):
  1385. """Use this decorator to remove trailing slashes from the request path.
  1386. For example, a request to ``/foo/`` would redirect to ``/foo`` with this
  1387. decorator. Your request handler mapping should use a regular expression
  1388. like ``r'/foo/*'`` in conjunction with using the decorator.
  1389. """
  1390. @functools.wraps(method)
  1391. def wrapper(self, *args, **kwargs):
  1392. if self.request.path.endswith("/"):
  1393. if self.request.method in ("GET", "HEAD"):
  1394. uri = self.request.path.rstrip("/")
  1395. if uri: # don't try to redirect '/' to ''
  1396. if self.request.query:
  1397. uri += "?" + self.request.query
  1398. self.redirect(uri, permanent=True)
  1399. return
  1400. else:
  1401. raise HTTPError(404)
  1402. return method(self, *args, **kwargs)
  1403. return wrapper
  1404. def addslash(method):
  1405. """Use this decorator to add a missing trailing slash to the request path.
  1406. For example, a request to ``/foo`` would redirect to ``/foo/`` with this
  1407. decorator. Your request handler mapping should use a regular expression
  1408. like ``r'/foo/?'`` in conjunction with using the decorator.
  1409. """
  1410. @functools.wraps(method)
  1411. def wrapper(self, *args, **kwargs):
  1412. if not self.request.path.endswith("/"):
  1413. if self.request.method in ("GET", "HEAD"):
  1414. uri = self.request.path + "/"
  1415. if self.request.query:
  1416. uri += "?" + self.request.query
  1417. self.redirect(uri, permanent=True)
  1418. return
  1419. raise HTTPError(404)
  1420. return method(self, *args, **kwargs)
  1421. return wrapper
  1422. class Application(httputil.HTTPServerConnectionDelegate):
  1423. """A collection of request handlers that make up a web application.
  1424. Instances of this class are callable and can be passed directly to
  1425. HTTPServer to serve the application::
  1426. application = web.Application([
  1427. (r"/", MainPageHandler),
  1428. ])
  1429. http_server = httpserver.HTTPServer(application)
  1430. http_server.listen(8080)
  1431. ioloop.IOLoop.current().start()
  1432. The constructor for this class takes in a list of `URLSpec` objects
  1433. or (regexp, request_class) tuples. When we receive requests, we
  1434. iterate over the list in order and instantiate an instance of the
  1435. first request class whose regexp matches the request path.
  1436. The request class can be specified as either a class object or a
  1437. (fully-qualified) name.
  1438. Each tuple can contain additional elements, which correspond to the
  1439. arguments to the `URLSpec` constructor. (Prior to Tornado 3.2,
  1440. only tuples of two or three elements were allowed).
  1441. A dictionary may be passed as the third element of the tuple,
  1442. which will be used as keyword arguments to the handler's
  1443. constructor and `~RequestHandler.initialize` method. This pattern
  1444. is used for the `StaticFileHandler` in this example (note that a
  1445. `StaticFileHandler` can be installed automatically with the
  1446. static_path setting described below)::
  1447. application = web.Application([
  1448. (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
  1449. ])
  1450. We support virtual hosts with the `add_handlers` method, which takes in
  1451. a host regular expression as the first argument::
  1452. application.add_handlers(r"www\.myhost\.com", [
  1453. (r"/article/([0-9]+)", ArticleHandler),
  1454. ])
  1455. You can serve static files by sending the ``static_path`` setting
  1456. as a keyword argument. We will serve those files from the
  1457. ``/static/`` URI (this is configurable with the
  1458. ``static_url_prefix`` setting), and we will serve ``/favicon.ico``
  1459. and ``/robots.txt`` from the same directory. A custom subclass of
  1460. `StaticFileHandler` can be specified with the
  1461. ``static_handler_class`` setting.
  1462. """
  1463. def __init__(self, handlers=None, default_host="", transforms=None,
  1464. **settings):
  1465. if transforms is None:
  1466. self.transforms = []
  1467. if settings.get("compress_response") or settings.get("gzip"):
  1468. self.transforms.append(GZipContentEncoding)
  1469. else:
  1470. self.transforms = transforms
  1471. self.handlers = []
  1472. self.named_handlers = {}
  1473. self.default_host = default_host
  1474. self.settings = settings
  1475. self.ui_modules = {'linkify': _linkify,
  1476. 'xsrf_form_html': _xsrf_form_html,
  1477. 'Template': TemplateModule,
  1478. }
  1479. self.ui_methods = {}
  1480. self._load_ui_modules(settings.get("ui_modules", {}))
  1481. self._load_ui_methods(settings.get("ui_methods", {}))
  1482. if self.settings.get("static_path"):
  1483. path = self.settings["static_path"]
  1484. handlers = list(handlers or [])
  1485. static_url_prefix = settings.get("static_url_prefix",
  1486. "/static/")
  1487. static_handler_class = settings.get("static_handler_class",
  1488. StaticFileHandler)
  1489. static_handler_args = settings.get("static_handler_args", {})
  1490. static_handler_args['path'] = path
  1491. for pattern in [re.escape(static_url_prefix) + r"(.*)",
  1492. r"/(favicon\.ico)", r"/(robots\.txt)"]:
  1493. handlers.insert(0, (pattern, static_handler_class,
  1494. static_handler_args))
  1495. if handlers:
  1496. self.add_handlers(".*$", handlers)
  1497. if self.settings.get('debug'):
  1498. self.settings.setdefault('autoreload', True)
  1499. self.settings.setdefault('compiled_template_cache', False)
  1500. self.settings.setdefault('static_hash_cache', False)
  1501. self.settings.setdefault('serve_traceback', True)
  1502. # Automatically reload modified modules
  1503. if self.settings.get('autoreload'):
  1504. from tornado import autoreload
  1505. autoreload.start()
  1506. def listen(self, port, address="", **kwargs):
  1507. """Starts an HTTP server for this application on the given port.
  1508. This is a convenience alias for creating an `.HTTPServer`
  1509. object and calling its listen method. Keyword arguments not
  1510. supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the
  1511. `.HTTPServer` constructor. For advanced uses
  1512. (e.g. multi-process mode), do not use this method; create an
  1513. `.HTTPServer` and call its
  1514. `.TCPServer.bind`/`.TCPServer.start` methods directly.
  1515. Note that after calling this method you still need to call
  1516. ``IOLoop.current().start()`` to start the server.
  1517. Returns the `.HTTPServer` object.
  1518. .. versionchanged:: 4.3
  1519. Now returns the `.HTTPServer` object.
  1520. """
  1521. # import is here rather than top level because HTTPServer
  1522. # is not importable on appengine
  1523. from tornado.httpserver import HTTPServer
  1524. server = HTTPServer(self, **kwargs)
  1525. server.listen(port, address)
  1526. return server
  1527. def add_handlers(self, host_pattern, host_handlers):
  1528. """Appends the given handlers to our handler list.
  1529. Host patterns are processed sequentially in the order they were
  1530. added. All matching patterns will be considered.
  1531. """
  1532. if not host_pattern.endswith("$"):
  1533. host_pattern += "$"
  1534. handlers = []
  1535. # The handlers with the wildcard host_pattern are a special
  1536. # case - they're added in the constructor but should have lower
  1537. # precedence than the more-precise handlers added later.
  1538. # If a wildcard handler group exists, it should always be last
  1539. # in the list, so insert new groups just before it.
  1540. if self.handlers and self.handlers[-1][0].pattern == '.*$':
  1541. self.handlers.insert(-1, (re.compile(host_pattern), handlers))
  1542. else:
  1543. self.handlers.append((re.compile(host_pattern), handlers))
  1544. for spec in host_handlers:
  1545. if isinstance(spec, (tuple, list)):
  1546. assert len(spec) in (2, 3, 4)
  1547. spec = URLSpec(*spec)
  1548. handlers.append(spec)
  1549. if spec.name:
  1550. if spec.name in self.named_handlers:
  1551. app_log.warning(
  1552. "Multiple handlers named %s; replacing previous value",
  1553. spec.name)
  1554. self.named_handlers[spec.name] = spec
  1555. def add_transform(self, transform_class):
  1556. self.transforms.append(transform_class)
  1557. def _get_host_handlers(self, request):
  1558. host = split_host_and_port(request.host.lower())[0]
  1559. matches = []
  1560. for pattern, handlers in self.handlers:
  1561. if pattern.match(host):
  1562. matches.extend(handlers)
  1563. # Look for default host if not behind load balancer (for debugging)
  1564. if not matches and "X-Real-Ip" not in request.headers:
  1565. for pattern, handlers in self.handlers:
  1566. if pattern.match(self.default_host):
  1567. matches.extend(handlers)
  1568. return matches or None
  1569. def _load_ui_methods(self, methods):
  1570. if isinstance(methods, types.ModuleType):
  1571. self._load_ui_methods(dict((n, getattr(methods, n))
  1572. for n in dir(methods)))
  1573. elif isinstance(methods, list):
  1574. for m in methods:
  1575. self._load_ui_methods(m)
  1576. else:
  1577. for name, fn in methods.items():
  1578. if not name.startswith("_") and hasattr(fn, "__call__") \
  1579. and name[0].lower() == name[0]:
  1580. self.ui_methods[name] = fn
  1581. def _load_ui_modules(self, modules):
  1582. if isinstance(modules, types.ModuleType):
  1583. self._load_ui_modules(dict((n, getattr(modules, n))
  1584. for n in dir(modules)))
  1585. elif isinstance(modules, list):
  1586. for m in modules:
  1587. self._load_ui_modules(m)
  1588. else:
  1589. assert isinstance(modules, dict)
  1590. for name, cls in modules.items():
  1591. try:
  1592. if issubclass(cls, UIModule):
  1593. self.ui_modules[name] = cls
  1594. except TypeError:
  1595. pass
  1596. def start_request(self, server_conn, request_conn):
  1597. # Modern HTTPServer interface
  1598. return _RequestDispatcher(self, request_conn)
  1599. def __call__(self, request):
  1600. # Legacy HTTPServer interface
  1601. dispatcher = _RequestDispatcher(self, None)
  1602. dispatcher.set_request(request)
  1603. return dispatcher.execute()
  1604. def reverse_url(self, name, *args):
  1605. """Returns a URL path for handler named ``name``
  1606. The handler must be added to the application as a named `URLSpec`.
  1607. Args will be substituted for capturing groups in the `URLSpec` regex.
  1608. They will be converted to strings if necessary, encoded as utf8,
  1609. and url-escaped.
  1610. """
  1611. if name in self.named_handlers:
  1612. return self.named_handlers[name].reverse(*args)
  1613. raise KeyError("%s not found in named urls" % name)
  1614. def log_request(self, handler):
  1615. """Writes a completed HTTP request to the logs.
  1616. By default writes to the python root logger. To change
  1617. this behavior either subclass Application and override this method,
  1618. or pass a function in the application settings dictionary as
  1619. ``log_function``.
  1620. """
  1621. if "log_function" in self.settings:
  1622. self.settings["log_function"](handler)
  1623. return
  1624. if handler.get_status() < 400:
  1625. log_method = access_log.info
  1626. elif handler.get_status() < 500:
  1627. log_method = access_log.warning
  1628. else:
  1629. log_method = access_log.error
  1630. request_time = 1000.0 * handler.request.request_time()
  1631. log_method("%d %s %.2fms", handler.get_status(),
  1632. handler._request_summary(), request_time)
  1633. class _RequestDispatcher(httputil.HTTPMessageDelegate):
  1634. def __init__(self, application, connection):
  1635. self.application = application
  1636. self.connection = connection
  1637. self.request = None
  1638. self.chunks = []
  1639. self.handler_class = None
  1640. self.handler_kwargs = None
  1641. self.path_args = []
  1642. self.path_kwargs = {}
  1643. def headers_received(self, start_line, headers):
  1644. self.set_request(httputil.HTTPServerRequest(
  1645. connection=self.connection, start_line=start_line,
  1646. headers=headers))
  1647. if self.stream_request_body:
  1648. self.request.body = Future()
  1649. return self.execute()
  1650. def set_request(self, request):
  1651. self.request = request
  1652. self._find_handler()
  1653. self.stream_request_body = _has_stream_request_body(self.handler_class)
  1654. def _find_handler(self):
  1655. # Identify the handler to use as soon as we have the request.
  1656. # Save url path arguments for later.
  1657. app = self.application
  1658. handlers = app._get_host_handlers(self.request)
  1659. if not handlers:
  1660. self.handler_class = RedirectHandler
  1661. self.handler_kwargs = dict(url="%s://%s/"
  1662. % (self.request.protocol,
  1663. app.default_host))
  1664. return
  1665. for spec in handlers:
  1666. match = spec.regex.match(self.request.path)
  1667. if match:
  1668. self.handler_class = spec.handler_class
  1669. self.handler_kwargs = spec.kwargs
  1670. if spec.regex.groups:
  1671. # Pass matched groups to the handler. Since
  1672. # match.groups() includes both named and
  1673. # unnamed groups, we want to use either groups
  1674. # or groupdict but not both.
  1675. if spec.regex.groupindex:
  1676. self.path_kwargs = dict(
  1677. (str(k), _unquote_or_none(v))
  1678. for (k, v) in match.groupdict().items())
  1679. else:
  1680. self.path_args = [_unquote_or_none(s)
  1681. for s in match.groups()]
  1682. return
  1683. if app.settings.get('default_handler_class'):
  1684. self.handler_class = app.settings['default_handler_class']
  1685. self.handler_kwargs = app.settings.get(
  1686. 'default_handler_args', {})
  1687. else:
  1688. self.handler_class = ErrorHandler
  1689. self.handler_kwargs = dict(status_code=404)
  1690. def data_received(self, data):
  1691. if self.stream_request_body:
  1692. return self.handler.data_received(data)
  1693. else:
  1694. self.chunks.append(data)
  1695. def finish(self):
  1696. if self.stream_request_body:
  1697. self.request.body.set_result(None)
  1698. else:
  1699. self.request.body = b''.join(self.chunks)
  1700. self.request._parse_body()
  1701. self.execute()
  1702. def on_connection_close(self):
  1703. if self.stream_request_body:
  1704. self.handler.on_connection_close()
  1705. else:
  1706. self.chunks = None
  1707. def execute(self):
  1708. # If template cache is disabled (usually in the debug mode),
  1709. # re-compile templates and reload static files on every
  1710. # request so you don't need to restart to see changes
  1711. if not self.application.settings.get("compiled_template_cache", True):
  1712. with RequestHandler._template_loader_lock:
  1713. for loader in RequestHandler._template_loaders.values():
  1714. loader.reset()
  1715. if not self.application.settings.get('static_hash_cache', True):
  1716. StaticFileHandler.reset()
  1717. self.handler = self.handler_class(self.application, self.request,
  1718. **self.handler_kwargs)
  1719. transforms = [t(self.request) for t in self.application.transforms]
  1720. if self.stream_request_body:
  1721. self.handler._prepared_future = Future()
  1722. # Note that if an exception escapes handler._execute it will be
  1723. # trapped in the Future it returns (which we are ignoring here,
  1724. # leaving it to be logged when the Future is GC'd).
  1725. # However, that shouldn't happen because _execute has a blanket
  1726. # except handler, and we cannot easily access the IOLoop here to
  1727. # call add_future (because of the requirement to remain compatible
  1728. # with WSGI)
  1729. self.handler._execute(transforms, *self.path_args,
  1730. **self.path_kwargs)
  1731. # If we are streaming the request body, then execute() is finished
  1732. # when the handler has prepared to receive the body. If not,
  1733. # it doesn't matter when execute() finishes (so we return None)
  1734. return self.handler._prepared_future
  1735. class HTTPError(Exception):
  1736. """An exception that will turn into an HTTP error response.
  1737. Raising an `HTTPError` is a convenient alternative to calling
  1738. `RequestHandler.send_error` since it automatically ends the
  1739. current function.
  1740. To customize the response sent with an `HTTPError`, override
  1741. `RequestHandler.write_error`.
  1742. :arg int status_code: HTTP status code. Must be listed in
  1743. `httplib.responses <http.client.responses>` unless the ``reason``
  1744. keyword argument is given.
  1745. :arg string log_message: Message to be written to the log for this error
  1746. (will not be shown to the user unless the `Application` is in debug
  1747. mode). May contain ``%s``-style placeholders, which will be filled
  1748. in with remaining positional parameters.
  1749. :arg string reason: Keyword-only argument. The HTTP "reason" phrase
  1750. to pass in the status line along with ``status_code``. Normally
  1751. determined automatically from ``status_code``, but can be used
  1752. to use a non-standard numeric code.
  1753. """
  1754. def __init__(self, status_code=500, log_message=None, *args, **kwargs):
  1755. self.status_code = status_code
  1756. self.log_message = log_message
  1757. self.args = args
  1758. self.reason = kwargs.get('reason', None)
  1759. if log_message and not args:
  1760. self.log_message = log_message.replace('%', '%%')
  1761. def __str__(self):
  1762. message = "HTTP %d: %s" % (
  1763. self.status_code,
  1764. self.reason or httputil.responses.get(self.status_code, 'Unknown'))
  1765. if self.log_message:
  1766. return message + " (" + (self.log_message % self.args) + ")"
  1767. else:
  1768. return message
  1769. class Finish(Exception):
  1770. """An exception that ends the request without producing an error response.
  1771. When `Finish` is raised in a `RequestHandler`, the request will
  1772. end (calling `RequestHandler.finish` if it hasn't already been
  1773. called), but the error-handling methods (including
  1774. `RequestHandler.write_error`) will not be called.
  1775. If `Finish()` was created with no arguments, the pending response
  1776. will be sent as-is. If `Finish()` was given an argument, that
  1777. argument will be passed to `RequestHandler.finish()`.
  1778. This can be a more convenient way to implement custom error pages
  1779. than overriding ``write_error`` (especially in library code)::
  1780. if self.current_user is None:
  1781. self.set_status(401)
  1782. self.set_header('WWW-Authenticate', 'Basic realm="something"')
  1783. raise Finish()
  1784. .. versionchanged:: 4.3
  1785. Arguments passed to ``Finish()`` will be passed on to
  1786. `RequestHandler.finish`.
  1787. """
  1788. pass
  1789. class MissingArgumentError(HTTPError):
  1790. """Exception raised by `RequestHandler.get_argument`.
  1791. This is a subclass of `HTTPError`, so if it is uncaught a 400 response
  1792. code will be used instead of 500 (and a stack trace will not be logged).
  1793. .. versionadded:: 3.1
  1794. """
  1795. def __init__(self, arg_name):
  1796. super(MissingArgumentError, self).__init__(
  1797. 400, 'Missing argument %s' % arg_name)
  1798. self.arg_name = arg_name
  1799. class ErrorHandler(RequestHandler):
  1800. """Generates an error response with ``status_code`` for all requests."""
  1801. def initialize(self, status_code):
  1802. self.set_status(status_code)
  1803. def prepare(self):
  1804. raise HTTPError(self._status_code)
  1805. def check_xsrf_cookie(self):
  1806. # POSTs to an ErrorHandler don't actually have side effects,
  1807. # so we don't need to check the xsrf token. This allows POSTs
  1808. # to the wrong url to return a 404 instead of 403.
  1809. pass
  1810. class RedirectHandler(RequestHandler):
  1811. """Redirects the client to the given URL for all GET requests.
  1812. You should provide the keyword argument ``url`` to the handler, e.g.::
  1813. application = web.Application([
  1814. (r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
  1815. ])
  1816. """
  1817. def initialize(self, url, permanent=True):
  1818. self._url = url
  1819. self._permanent = permanent
  1820. def get(self):
  1821. self.redirect(self._url, permanent=self._permanent)
  1822. class StaticFileHandler(RequestHandler):
  1823. """A simple handler that can serve static content from a directory.
  1824. A `StaticFileHandler` is configured automatically if you pass the
  1825. ``static_path`` keyword argument to `Application`. This handler
  1826. can be customized with the ``static_url_prefix``, ``static_handler_class``,
  1827. and ``static_handler_args`` settings.
  1828. To map an additional path to this handler for a static data directory
  1829. you would add a line to your application like::
  1830. application = web.Application([
  1831. (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
  1832. ])
  1833. The handler constructor requires a ``path`` argument, which specifies the
  1834. local root directory of the content to be served.
  1835. Note that a capture group in the regex is required to parse the value for
  1836. the ``path`` argument to the get() method (different than the constructor
  1837. argument above); see `URLSpec` for details.
  1838. To serve a file like ``index.html`` automatically when a directory is
  1839. requested, set ``static_handler_args=dict(default_filename="index.html")``
  1840. in your application settings, or add ``default_filename`` as an initializer
  1841. argument for your ``StaticFileHandler``.
  1842. To maximize the effectiveness of browser caching, this class supports
  1843. versioned urls (by default using the argument ``?v=``). If a version
  1844. is given, we instruct the browser to cache this file indefinitely.
  1845. `make_static_url` (also available as `RequestHandler.static_url`) can
  1846. be used to construct a versioned url.
  1847. This handler is intended primarily for use in development and light-duty
  1848. file serving; for heavy traffic it will be more efficient to use
  1849. a dedicated static file server (such as nginx or Apache). We support
  1850. the HTTP ``Accept-Ranges`` mechanism to return partial content (because
  1851. some browsers require this functionality to be present to seek in
  1852. HTML5 audio or video).
  1853. **Subclassing notes**
  1854. This class is designed to be extensible by subclassing, but because
  1855. of the way static urls are generated with class methods rather than
  1856. instance methods, the inheritance patterns are somewhat unusual.
  1857. Be sure to use the ``@classmethod`` decorator when overriding a
  1858. class method. Instance methods may use the attributes ``self.path``
  1859. ``self.absolute_path``, and ``self.modified``.
  1860. Subclasses should only override methods discussed in this section;
  1861. overriding other methods is error-prone. Overriding
  1862. ``StaticFileHandler.get`` is particularly problematic due to the
  1863. tight coupling with ``compute_etag`` and other methods.
  1864. To change the way static urls are generated (e.g. to match the behavior
  1865. of another server or CDN), override `make_static_url`, `parse_url_path`,
  1866. `get_cache_time`, and/or `get_version`.
  1867. To replace all interaction with the filesystem (e.g. to serve
  1868. static content from a database), override `get_content`,
  1869. `get_content_size`, `get_modified_time`, `get_absolute_path`, and
  1870. `validate_absolute_path`.
  1871. .. versionchanged:: 3.1
  1872. Many of the methods for subclasses were added in Tornado 3.1.
  1873. """
  1874. CACHE_MAX_AGE = 86400 * 365 * 10 # 10 years
  1875. _static_hashes = {}
  1876. _lock = threading.Lock() # protects _static_hashes
  1877. def initialize(self, path, default_filename=None):
  1878. self.root = path
  1879. self.default_filename = default_filename
  1880. @classmethod
  1881. def reset(cls):
  1882. with cls._lock:
  1883. cls._static_hashes = {}
  1884. def head(self, path):
  1885. return self.get(path, include_body=False)
  1886. @gen.coroutine
  1887. def get(self, path, include_body=True):
  1888. # Set up our path instance variables.
  1889. self.path = self.parse_url_path(path)
  1890. del path # make sure we don't refer to path instead of self.path again
  1891. absolute_path = self.get_absolute_path(self.root, self.path)
  1892. self.absolute_path = self.validate_absolute_path(
  1893. self.root, absolute_path)
  1894. if self.absolute_path is None:
  1895. return
  1896. self.modified = self.get_modified_time()
  1897. self.set_headers()
  1898. if self.should_return_304():
  1899. self.set_status(304)
  1900. return
  1901. request_range = None
  1902. range_header = self.request.headers.get("Range")
  1903. if range_header:
  1904. # As per RFC 2616 14.16, if an invalid Range header is specified,
  1905. # the request will be treated as if the header didn't exist.
  1906. request_range = httputil._parse_request_range(range_header)
  1907. size = self.get_content_size()
  1908. if request_range:
  1909. start, end = request_range
  1910. if (start is not None and start >= size) or end == 0:
  1911. # As per RFC 2616 14.35.1, a range is not satisfiable only: if
  1912. # the first requested byte is equal to or greater than the
  1913. # content, or when a suffix with length 0 is specified
  1914. self.set_status(416) # Range Not Satisfiable
  1915. self.set_header("Content-Type", "text/plain")
  1916. self.set_header("Content-Range", "bytes */%s" % (size, ))
  1917. return
  1918. if start is not None and start < 0:
  1919. start += size
  1920. if end is not None and end > size:
  1921. # Clients sometimes blindly use a large range to limit their
  1922. # download size; cap the endpoint at the actual file size.
  1923. end = size
  1924. # Note: only return HTTP 206 if less than the entire range has been
  1925. # requested. Not only is this semantically correct, but Chrome
  1926. # refuses to play audio if it gets an HTTP 206 in response to
  1927. # ``Range: bytes=0-``.
  1928. if size != (end or size) - (start or 0):
  1929. self.set_status(206) # Partial Content
  1930. self.set_header("Content-Range",
  1931. httputil._get_content_range(start, end, size))
  1932. else:
  1933. start = end = None
  1934. if start is not None and end is not None:
  1935. content_length = end - start
  1936. elif end is not None:
  1937. content_length = end
  1938. elif start is not None:
  1939. content_length = size - start
  1940. else:
  1941. content_length = size
  1942. self.set_header("Content-Length", content_length)
  1943. if include_body:
  1944. content = self.get_content(self.absolute_path, start, end)
  1945. if isinstance(content, bytes):
  1946. content = [content]
  1947. for chunk in content:
  1948. try:
  1949. self.write(chunk)
  1950. yield self.flush()
  1951. except iostream.StreamClosedError:
  1952. return
  1953. else:
  1954. assert self.request.method == "HEAD"
  1955. def compute_etag(self):
  1956. """Sets the ``Etag`` header based on static url version.
  1957. This allows efficient ``If-None-Match`` checks against cached
  1958. versions, and sends the correct ``Etag`` for a partial response
  1959. (i.e. the same ``Etag`` as the full file).
  1960. .. versionadded:: 3.1
  1961. """
  1962. version_hash = self._get_cached_version(self.absolute_path)
  1963. if not version_hash:
  1964. return None
  1965. return '"%s"' % (version_hash, )
  1966. def set_headers(self):
  1967. """Sets the content and caching headers on the response.
  1968. .. versionadded:: 3.1
  1969. """
  1970. self.set_header("Accept-Ranges", "bytes")
  1971. self.set_etag_header()
  1972. if self.modified is not None:
  1973. self.set_header("Last-Modified", self.modified)
  1974. content_type = self.get_content_type()
  1975. if content_type:
  1976. self.set_header("Content-Type", content_type)
  1977. cache_time = self.get_cache_time(self.path, self.modified,
  1978. content_type)
  1979. if cache_time > 0:
  1980. self.set_header("Expires", datetime.datetime.utcnow() +
  1981. datetime.timedelta(seconds=cache_time))
  1982. self.set_header("Cache-Control", "max-age=" + str(cache_time))
  1983. self.set_extra_headers(self.path)
  1984. def should_return_304(self):
  1985. """Returns True if the headers indicate that we should return 304.
  1986. .. versionadded:: 3.1
  1987. """
  1988. if self.check_etag_header():
  1989. return True
  1990. # Check the If-Modified-Since, and don't send the result if the
  1991. # content has not been modified
  1992. ims_value = self.request.headers.get("If-Modified-Since")
  1993. if ims_value is not None:
  1994. date_tuple = email.utils.parsedate(ims_value)
  1995. if date_tuple is not None:
  1996. if_since = datetime.datetime(*date_tuple[:6])
  1997. if if_since >= self.modified:
  1998. return True
  1999. return False
  2000. @classmethod
  2001. def get_absolute_path(cls, root, path):
  2002. """Returns the absolute location of ``path`` relative to ``root``.
  2003. ``root`` is the path configured for this `StaticFileHandler`
  2004. (in most cases the ``static_path`` `Application` setting).
  2005. This class method may be overridden in subclasses. By default
  2006. it returns a filesystem path, but other strings may be used
  2007. as long as they are unique and understood by the subclass's
  2008. overridden `get_content`.
  2009. .. versionadded:: 3.1
  2010. """
  2011. abspath = os.path.abspath(os.path.join(root, path))
  2012. return abspath
  2013. def validate_absolute_path(self, root, absolute_path):
  2014. """Validate and return the absolute path.
  2015. ``root`` is the configured path for the `StaticFileHandler`,
  2016. and ``path`` is the result of `get_absolute_path`
  2017. This is an instance method called during request processing,
  2018. so it may raise `HTTPError` or use methods like
  2019. `RequestHandler.redirect` (return None after redirecting to
  2020. halt further processing). This is where 404 errors for missing files
  2021. are generated.
  2022. This method may modify the path before returning it, but note that
  2023. any such modifications will not be understood by `make_static_url`.
  2024. In instance methods, this method's result is available as
  2025. ``self.absolute_path``.
  2026. .. versionadded:: 3.1
  2027. """
  2028. # os.path.abspath strips a trailing /.
  2029. # We must add it back to `root` so that we only match files
  2030. # in a directory named `root` instead of files starting with
  2031. # that prefix.
  2032. root = os.path.abspath(root)
  2033. if not root.endswith(os.path.sep):
  2034. # abspath always removes a trailing slash, except when
  2035. # root is '/'. This is an unusual case, but several projects
  2036. # have independently discovered this technique to disable
  2037. # Tornado's path validation and (hopefully) do their own,
  2038. # so we need to support it.
  2039. root += os.path.sep
  2040. # The trailing slash also needs to be temporarily added back
  2041. # the requested path so a request to root/ will match.
  2042. if not (absolute_path + os.path.sep).startswith(root):
  2043. raise HTTPError(403, "%s is not in root static directory",
  2044. self.path)
  2045. if (os.path.isdir(absolute_path) and
  2046. self.default_filename is not None):
  2047. # need to look at the request.path here for when path is empty
  2048. # but there is some prefix to the path that was already
  2049. # trimmed by the routing
  2050. if not self.request.path.endswith("/"):
  2051. self.redirect(self.request.path + "/", permanent=True)
  2052. return
  2053. absolute_path = os.path.join(absolute_path, self.default_filename)
  2054. if not os.path.exists(absolute_path):
  2055. raise HTTPError(404)
  2056. if not os.path.isfile(absolute_path):
  2057. raise HTTPError(403, "%s is not a file", self.path)
  2058. return absolute_path
  2059. @classmethod
  2060. def get_content(cls, abspath, start=None, end=None):
  2061. """Retrieve the content of the requested resource which is located
  2062. at the given absolute path.
  2063. This class method may be overridden by subclasses. Note that its
  2064. signature is different from other overridable class methods
  2065. (no ``settings`` argument); this is deliberate to ensure that
  2066. ``abspath`` is able to stand on its own as a cache key.
  2067. This method should either return a byte string or an iterator
  2068. of byte strings. The latter is preferred for large files
  2069. as it helps reduce memory fragmentation.
  2070. .. versionadded:: 3.1
  2071. """
  2072. with open(abspath, "rb") as file:
  2073. if start is not None:
  2074. file.seek(start)
  2075. if end is not None:
  2076. remaining = end - (start or 0)
  2077. else:
  2078. remaining = None
  2079. while True:
  2080. chunk_size = 64 * 1024
  2081. if remaining is not None and remaining < chunk_size:
  2082. chunk_size = remaining
  2083. chunk = file.read(chunk_size)
  2084. if chunk:
  2085. if remaining is not None:
  2086. remaining -= len(chunk)
  2087. yield chunk
  2088. else:
  2089. if remaining is not None:
  2090. assert remaining == 0
  2091. return
  2092. @classmethod
  2093. def get_content_version(cls, abspath):
  2094. """Returns a version string for the resource at the given path.
  2095. This class method may be overridden by subclasses. The
  2096. default implementation is a hash of the file's contents.
  2097. .. versionadded:: 3.1
  2098. """
  2099. data = cls.get_content(abspath)
  2100. hasher = hashlib.md5()
  2101. if isinstance(data, bytes):
  2102. hasher.update(data)
  2103. else:
  2104. for chunk in data:
  2105. hasher.update(chunk)
  2106. return hasher.hexdigest()
  2107. def _stat(self):
  2108. if not hasattr(self, '_stat_result'):
  2109. self._stat_result = os.stat(self.absolute_path)
  2110. return self._stat_result
  2111. def get_content_size(self):
  2112. """Retrieve the total size of the resource at the given path.
  2113. This method may be overridden by subclasses.
  2114. .. versionadded:: 3.1
  2115. .. versionchanged:: 4.0
  2116. This method is now always called, instead of only when
  2117. partial results are requested.
  2118. """
  2119. stat_result = self._stat()
  2120. return stat_result[stat.ST_SIZE]
  2121. def get_modified_time(self):
  2122. """Returns the time that ``self.absolute_path`` was last modified.
  2123. May be overridden in subclasses. Should return a `~datetime.datetime`
  2124. object or None.
  2125. .. versionadded:: 3.1
  2126. """
  2127. stat_result = self._stat()
  2128. modified = datetime.datetime.utcfromtimestamp(
  2129. stat_result[stat.ST_MTIME])
  2130. return modified
  2131. def get_content_type(self):
  2132. """Returns the ``Content-Type`` header to be used for this request.
  2133. .. versionadded:: 3.1
  2134. """
  2135. mime_type, encoding = mimetypes.guess_type(self.absolute_path)
  2136. # per RFC 6713, use the appropriate type for a gzip compressed file
  2137. if encoding == "gzip":
  2138. return "application/gzip"
  2139. # As of 2015-07-21 there is no bzip2 encoding defined at
  2140. # http://www.iana.org/assignments/media-types/media-types.xhtml
  2141. # So for that (and any other encoding), use octet-stream.
  2142. elif encoding is not None:
  2143. return "application/octet-stream"
  2144. elif mime_type is not None:
  2145. return mime_type
  2146. # if mime_type not detected, use application/octet-stream
  2147. else:
  2148. return "application/octet-stream"
  2149. def set_extra_headers(self, path):
  2150. """For subclass to add extra headers to the response"""
  2151. pass
  2152. def get_cache_time(self, path, modified, mime_type):
  2153. """Override to customize cache control behavior.
  2154. Return a positive number of seconds to make the result
  2155. cacheable for that amount of time or 0 to mark resource as
  2156. cacheable for an unspecified amount of time (subject to
  2157. browser heuristics).
  2158. By default returns cache expiry of 10 years for resources requested
  2159. with ``v`` argument.
  2160. """
  2161. return self.CACHE_MAX_AGE if "v" in self.request.arguments else 0
  2162. @classmethod
  2163. def make_static_url(cls, settings, path, include_version=True):
  2164. """Constructs a versioned url for the given path.
  2165. This method may be overridden in subclasses (but note that it
  2166. is a class method rather than an instance method). Subclasses
  2167. are only required to implement the signature
  2168. ``make_static_url(cls, settings, path)``; other keyword
  2169. arguments may be passed through `~RequestHandler.static_url`
  2170. but are not standard.
  2171. ``settings`` is the `Application.settings` dictionary. ``path``
  2172. is the static path being requested. The url returned should be
  2173. relative to the current host.
  2174. ``include_version`` determines whether the generated URL should
  2175. include the query string containing the version hash of the
  2176. file corresponding to the given ``path``.
  2177. """
  2178. url = settings.get('static_url_prefix', '/static/') + path
  2179. if not include_version:
  2180. return url
  2181. version_hash = cls.get_version(settings, path)
  2182. if not version_hash:
  2183. return url
  2184. return '%s?v=%s' % (url, version_hash)
  2185. def parse_url_path(self, url_path):
  2186. """Converts a static URL path into a filesystem path.
  2187. ``url_path`` is the path component of the URL with
  2188. ``static_url_prefix`` removed. The return value should be
  2189. filesystem path relative to ``static_path``.
  2190. This is the inverse of `make_static_url`.
  2191. """
  2192. if os.path.sep != "/":
  2193. url_path = url_path.replace("/", os.path.sep)
  2194. return url_path
  2195. @classmethod
  2196. def get_version(cls, settings, path):
  2197. """Generate the version string to be used in static URLs.
  2198. ``settings`` is the `Application.settings` dictionary and ``path``
  2199. is the relative location of the requested asset on the filesystem.
  2200. The returned value should be a string, or ``None`` if no version
  2201. could be determined.
  2202. .. versionchanged:: 3.1
  2203. This method was previously recommended for subclasses to override;
  2204. `get_content_version` is now preferred as it allows the base
  2205. class to handle caching of the result.
  2206. """
  2207. abs_path = cls.get_absolute_path(settings['static_path'], path)
  2208. return cls._get_cached_version(abs_path)
  2209. @classmethod
  2210. def _get_cached_version(cls, abs_path):
  2211. with cls._lock:
  2212. hashes = cls._static_hashes
  2213. if abs_path not in hashes:
  2214. try:
  2215. hashes[abs_path] = cls.get_content_version(abs_path)
  2216. except Exception:
  2217. gen_log.error("Could not open static file %r", abs_path)
  2218. hashes[abs_path] = None
  2219. hsh = hashes.get(abs_path)
  2220. if hsh:
  2221. return hsh
  2222. return None
  2223. class FallbackHandler(RequestHandler):
  2224. """A `RequestHandler` that wraps another HTTP server callback.
  2225. The fallback is a callable object that accepts an
  2226. `~.httputil.HTTPServerRequest`, such as an `Application` or
  2227. `tornado.wsgi.WSGIContainer`. This is most useful to use both
  2228. Tornado ``RequestHandlers`` and WSGI in the same server. Typical
  2229. usage::
  2230. wsgi_app = tornado.wsgi.WSGIContainer(
  2231. django.core.handlers.wsgi.WSGIHandler())
  2232. application = tornado.web.Application([
  2233. (r"/foo", FooHandler),
  2234. (r".*", FallbackHandler, dict(fallback=wsgi_app),
  2235. ])
  2236. """
  2237. def initialize(self, fallback):
  2238. self.fallback = fallback
  2239. def prepare(self):
  2240. self.fallback(self.request)
  2241. self._finished = True
  2242. class OutputTransform(object):
  2243. """A transform modifies the result of an HTTP request (e.g., GZip encoding)
  2244. Applications are not expected to create their own OutputTransforms
  2245. or interact with them directly; the framework chooses which transforms
  2246. (if any) to apply.
  2247. """
  2248. def __init__(self, request):
  2249. pass
  2250. def transform_first_chunk(self, status_code, headers, chunk, finishing):
  2251. return status_code, headers, chunk
  2252. def transform_chunk(self, chunk, finishing):
  2253. return chunk
  2254. class GZipContentEncoding(OutputTransform):
  2255. """Applies the gzip content encoding to the response.
  2256. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
  2257. .. versionchanged:: 4.0
  2258. Now compresses all mime types beginning with ``text/``, instead
  2259. of just a whitelist. (the whitelist is still used for certain
  2260. non-text mime types).
  2261. """
  2262. # Whitelist of compressible mime types (in addition to any types
  2263. # beginning with "text/").
  2264. CONTENT_TYPES = set(["application/javascript", "application/x-javascript",
  2265. "application/xml", "application/atom+xml",
  2266. "application/json", "application/xhtml+xml"])
  2267. # Python's GzipFile defaults to level 9, while most other gzip
  2268. # tools (including gzip itself) default to 6, which is probably a
  2269. # better CPU/size tradeoff.
  2270. GZIP_LEVEL = 6
  2271. # Responses that are too short are unlikely to benefit from gzipping
  2272. # after considering the "Content-Encoding: gzip" header and the header
  2273. # inside the gzip encoding.
  2274. # Note that responses written in multiple chunks will be compressed
  2275. # regardless of size.
  2276. MIN_LENGTH = 1024
  2277. def __init__(self, request):
  2278. self._gzipping = "gzip" in request.headers.get("Accept-Encoding", "")
  2279. def _compressible_type(self, ctype):
  2280. return ctype.startswith('text/') or ctype in self.CONTENT_TYPES
  2281. def transform_first_chunk(self, status_code, headers, chunk, finishing):
  2282. if 'Vary' in headers:
  2283. headers['Vary'] += b', Accept-Encoding'
  2284. else:
  2285. headers['Vary'] = b'Accept-Encoding'
  2286. if self._gzipping:
  2287. ctype = _unicode(headers.get("Content-Type", "")).split(";")[0]
  2288. self._gzipping = self._compressible_type(ctype) and \
  2289. (not finishing or len(chunk) >= self.MIN_LENGTH) and \
  2290. ("Content-Encoding" not in headers)
  2291. if self._gzipping:
  2292. headers["Content-Encoding"] = "gzip"
  2293. self._gzip_value = BytesIO()
  2294. self._gzip_file = gzip.GzipFile(mode="w", fileobj=self._gzip_value,
  2295. compresslevel=self.GZIP_LEVEL)
  2296. chunk = self.transform_chunk(chunk, finishing)
  2297. if "Content-Length" in headers:
  2298. # The original content length is no longer correct.
  2299. # If this is the last (and only) chunk, we can set the new
  2300. # content-length; otherwise we remove it and fall back to
  2301. # chunked encoding.
  2302. if finishing:
  2303. headers["Content-Length"] = str(len(chunk))
  2304. else:
  2305. del headers["Content-Length"]
  2306. return status_code, headers, chunk
  2307. def transform_chunk(self, chunk, finishing):
  2308. if self._gzipping:
  2309. self._gzip_file.write(chunk)
  2310. if finishing:
  2311. self._gzip_file.close()
  2312. else:
  2313. self._gzip_file.flush()
  2314. chunk = self._gzip_value.getvalue()
  2315. self._gzip_value.truncate(0)
  2316. self._gzip_value.seek(0)
  2317. return chunk
  2318. def authenticated(method):
  2319. """Decorate methods with this to require that the user be logged in.
  2320. If the user is not logged in, they will be redirected to the configured
  2321. `login url <RequestHandler.get_login_url>`.
  2322. If you configure a login url with a query parameter, Tornado will
  2323. assume you know what you're doing and use it as-is. If not, it
  2324. will add a `next` parameter so the login page knows where to send
  2325. you once you're logged in.
  2326. """
  2327. @functools.wraps(method)
  2328. def wrapper(self, *args, **kwargs):
  2329. if not self.current_user:
  2330. if self.request.method in ("GET", "HEAD"):
  2331. url = self.get_login_url()
  2332. if "?" not in url:
  2333. if urlparse.urlsplit(url).scheme:
  2334. # if login url is absolute, make next absolute too
  2335. next_url = self.request.full_url()
  2336. else:
  2337. next_url = self.request.uri
  2338. url += "?" + urlencode(dict(next=next_url))
  2339. self.redirect(url)
  2340. return
  2341. raise HTTPError(403)
  2342. return method(self, *args, **kwargs)
  2343. return wrapper
  2344. class UIModule(object):
  2345. """A re-usable, modular UI unit on a page.
  2346. UI modules often execute additional queries, and they can include
  2347. additional CSS and JavaScript that will be included in the output
  2348. page, which is automatically inserted on page render.
  2349. Subclasses of UIModule must override the `render` method.
  2350. """
  2351. def __init__(self, handler):
  2352. self.handler = handler
  2353. self.request = handler.request
  2354. self.ui = handler.ui
  2355. self.locale = handler.locale
  2356. @property
  2357. def current_user(self):
  2358. return self.handler.current_user
  2359. def render(self, *args, **kwargs):
  2360. """Override in subclasses to return this module's output."""
  2361. raise NotImplementedError()
  2362. def embedded_javascript(self):
  2363. """Override to return a JavaScript string
  2364. to be embedded in the page."""
  2365. return None
  2366. def javascript_files(self):
  2367. """Override to return a list of JavaScript files needed by this module.
  2368. If the return values are relative paths, they will be passed to
  2369. `RequestHandler.static_url`; otherwise they will be used as-is.
  2370. """
  2371. return None
  2372. def embedded_css(self):
  2373. """Override to return a CSS string
  2374. that will be embedded in the page."""
  2375. return None
  2376. def css_files(self):
  2377. """Override to returns a list of CSS files required by this module.
  2378. If the return values are relative paths, they will be passed to
  2379. `RequestHandler.static_url`; otherwise they will be used as-is.
  2380. """
  2381. return None
  2382. def html_head(self):
  2383. """Override to return an HTML string that will be put in the <head/>
  2384. element.
  2385. """
  2386. return None
  2387. def html_body(self):
  2388. """Override to return an HTML string that will be put at the end of
  2389. the <body/> element.
  2390. """
  2391. return None
  2392. def render_string(self, path, **kwargs):
  2393. """Renders a template and returns it as a string."""
  2394. return self.handler.render_string(path, **kwargs)
  2395. class _linkify(UIModule):
  2396. def render(self, text, **kwargs):
  2397. return escape.linkify(text, **kwargs)
  2398. class _xsrf_form_html(UIModule):
  2399. def render(self):
  2400. return self.handler.xsrf_form_html()
  2401. class TemplateModule(UIModule):
  2402. """UIModule that simply renders the given template.
  2403. {% module Template("foo.html") %} is similar to {% include "foo.html" %},
  2404. but the module version gets its own namespace (with kwargs passed to
  2405. Template()) instead of inheriting the outer template's namespace.
  2406. Templates rendered through this module also get access to UIModule's
  2407. automatic javascript/css features. Simply call set_resources
  2408. inside the template and give it keyword arguments corresponding to
  2409. the methods on UIModule: {{ set_resources(js_files=static_url("my.js")) }}
  2410. Note that these resources are output once per template file, not once
  2411. per instantiation of the template, so they must not depend on
  2412. any arguments to the template.
  2413. """
  2414. def __init__(self, handler):
  2415. super(TemplateModule, self).__init__(handler)
  2416. # keep resources in both a list and a dict to preserve order
  2417. self._resource_list = []
  2418. self._resource_dict = {}
  2419. def render(self, path, **kwargs):
  2420. def set_resources(**kwargs):
  2421. if path not in self._resource_dict:
  2422. self._resource_list.append(kwargs)
  2423. self._resource_dict[path] = kwargs
  2424. else:
  2425. if self._resource_dict[path] != kwargs:
  2426. raise ValueError("set_resources called with different "
  2427. "resources for the same template")
  2428. return ""
  2429. return self.render_string(path, set_resources=set_resources,
  2430. **kwargs)
  2431. def _get_resources(self, key):
  2432. return (r[key] for r in self._resource_list if key in r)
  2433. def embedded_javascript(self):
  2434. return "\n".join(self._get_resources("embedded_javascript"))
  2435. def javascript_files(self):
  2436. result = []
  2437. for f in self._get_resources("javascript_files"):
  2438. if isinstance(f, (unicode_type, bytes)):
  2439. result.append(f)
  2440. else:
  2441. result.extend(f)
  2442. return result
  2443. def embedded_css(self):
  2444. return "\n".join(self._get_resources("embedded_css"))
  2445. def css_files(self):
  2446. result = []
  2447. for f in self._get_resources("css_files"):
  2448. if isinstance(f, (unicode_type, bytes)):
  2449. result.append(f)
  2450. else:
  2451. result.extend(f)
  2452. return result
  2453. def html_head(self):
  2454. return "".join(self._get_resources("html_head"))
  2455. def html_body(self):
  2456. return "".join(self._get_resources("html_body"))
  2457. class _UIModuleNamespace(object):
  2458. """Lazy namespace which creates UIModule proxies bound to a handler."""
  2459. def __init__(self, handler, ui_modules):
  2460. self.handler = handler
  2461. self.ui_modules = ui_modules
  2462. def __getitem__(self, key):
  2463. return self.handler._ui_module(key, self.ui_modules[key])
  2464. def __getattr__(self, key):
  2465. try:
  2466. return self[key]
  2467. except KeyError as e:
  2468. raise AttributeError(str(e))
  2469. class URLSpec(object):
  2470. """Specifies mappings between URLs and handlers."""
  2471. def __init__(self, pattern, handler, kwargs=None, name=None):
  2472. """Parameters:
  2473. * ``pattern``: Regular expression to be matched. Any groups
  2474. in the regex will be passed in to the handler's get/post/etc
  2475. methods as arguments.
  2476. * ``handler``: `RequestHandler` subclass to be invoked.
  2477. * ``kwargs`` (optional): A dictionary of additional arguments
  2478. to be passed to the handler's constructor.
  2479. * ``name`` (optional): A name for this handler. Used by
  2480. `Application.reverse_url`.
  2481. """
  2482. if not pattern.endswith('$'):
  2483. pattern += '$'
  2484. self.regex = re.compile(pattern)
  2485. assert len(self.regex.groupindex) in (0, self.regex.groups), \
  2486. ("groups in url regexes must either be all named or all "
  2487. "positional: %r" % self.regex.pattern)
  2488. if isinstance(handler, str):
  2489. # import the Module and instantiate the class
  2490. # Must be a fully qualified name (module.ClassName)
  2491. handler = import_object(handler)
  2492. self.handler_class = handler
  2493. self.kwargs = kwargs or {}
  2494. self.name = name
  2495. self._path, self._group_count = self._find_groups()
  2496. def __repr__(self):
  2497. return '%s(%r, %s, kwargs=%r, name=%r)' % \
  2498. (self.__class__.__name__, self.regex.pattern,
  2499. self.handler_class, self.kwargs, self.name)
  2500. def _find_groups(self):
  2501. """Returns a tuple (reverse string, group count) for a url.
  2502. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
  2503. would return ('/%s/%s/', 2).
  2504. """
  2505. pattern = self.regex.pattern
  2506. if pattern.startswith('^'):
  2507. pattern = pattern[1:]
  2508. if pattern.endswith('$'):
  2509. pattern = pattern[:-1]
  2510. if self.regex.groups != pattern.count('('):
  2511. # The pattern is too complicated for our simplistic matching,
  2512. # so we can't support reversing it.
  2513. return (None, None)
  2514. pieces = []
  2515. for fragment in pattern.split('('):
  2516. if ')' in fragment:
  2517. paren_loc = fragment.index(')')
  2518. if paren_loc >= 0:
  2519. pieces.append('%s' + fragment[paren_loc + 1:])
  2520. else:
  2521. pieces.append(fragment)
  2522. return (''.join(pieces), self.regex.groups)
  2523. def reverse(self, *args):
  2524. assert self._path is not None, \
  2525. "Cannot reverse url regex " + self.regex.pattern
  2526. assert len(args) == self._group_count, "required number of arguments "\
  2527. "not found"
  2528. if not len(args):
  2529. return self._path
  2530. converted_args = []
  2531. for a in args:
  2532. if not isinstance(a, (unicode_type, bytes)):
  2533. a = str(a)
  2534. converted_args.append(escape.url_escape(utf8(a), plus=False))
  2535. return self._path % tuple(converted_args)
  2536. url = URLSpec
  2537. if hasattr(hmac, 'compare_digest'): # python 3.3
  2538. _time_independent_equals = hmac.compare_digest
  2539. else:
  2540. def _time_independent_equals(a, b):
  2541. if len(a) != len(b):
  2542. return False
  2543. result = 0
  2544. if isinstance(a[0], int): # python3 byte strings
  2545. for x, y in zip(a, b):
  2546. result |= x ^ y
  2547. else: # python2
  2548. for x, y in zip(a, b):
  2549. result |= ord(x) ^ ord(y)
  2550. return result == 0
  2551. def create_signed_value(secret, name, value, version=None, clock=None,
  2552. key_version=None):
  2553. if version is None:
  2554. version = DEFAULT_SIGNED_VALUE_VERSION
  2555. if clock is None:
  2556. clock = time.time
  2557. timestamp = utf8(str(int(clock())))
  2558. value = base64.b64encode(utf8(value))
  2559. if version == 1:
  2560. signature = _create_signature_v1(secret, name, value, timestamp)
  2561. value = b"|".join([value, timestamp, signature])
  2562. return value
  2563. elif version == 2:
  2564. # The v2 format consists of a version number and a series of
  2565. # length-prefixed fields "%d:%s", the last of which is a
  2566. # signature, all separated by pipes. All numbers are in
  2567. # decimal format with no leading zeros. The signature is an
  2568. # HMAC-SHA256 of the whole string up to that point, including
  2569. # the final pipe.
  2570. #
  2571. # The fields are:
  2572. # - format version (i.e. 2; no length prefix)
  2573. # - key version (integer, default is 0)
  2574. # - timestamp (integer seconds since epoch)
  2575. # - name (not encoded; assumed to be ~alphanumeric)
  2576. # - value (base64-encoded)
  2577. # - signature (hex-encoded; no length prefix)
  2578. def format_field(s):
  2579. return utf8("%d:" % len(s)) + utf8(s)
  2580. to_sign = b"|".join([
  2581. b"2",
  2582. format_field(str(key_version or 0)),
  2583. format_field(timestamp),
  2584. format_field(name),
  2585. format_field(value),
  2586. b''])
  2587. if isinstance(secret, dict):
  2588. assert key_version is not None, 'Key version must be set when sign key dict is used'
  2589. assert version >= 2, 'Version must be at least 2 for key version support'
  2590. secret = secret[key_version]
  2591. signature = _create_signature_v2(secret, to_sign)
  2592. return to_sign + signature
  2593. else:
  2594. raise ValueError("Unsupported version %d" % version)
  2595. # A leading version number in decimal
  2596. # with no leading zeros, followed by a pipe.
  2597. _signed_value_version_re = re.compile(br"^([1-9][0-9]*)\|(.*)$")
  2598. def _get_version(value):
  2599. # Figures out what version value is. Version 1 did not include an
  2600. # explicit version field and started with arbitrary base64 data,
  2601. # which makes this tricky.
  2602. m = _signed_value_version_re.match(value)
  2603. if m is None:
  2604. version = 1
  2605. else:
  2606. try:
  2607. version = int(m.group(1))
  2608. if version > 999:
  2609. # Certain payloads from the version-less v1 format may
  2610. # be parsed as valid integers. Due to base64 padding
  2611. # restrictions, this can only happen for numbers whose
  2612. # length is a multiple of 4, so we can treat all
  2613. # numbers up to 999 as versions, and for the rest we
  2614. # fall back to v1 format.
  2615. version = 1
  2616. except ValueError:
  2617. version = 1
  2618. return version
  2619. def decode_signed_value(secret, name, value, max_age_days=31,
  2620. clock=None, min_version=None):
  2621. if clock is None:
  2622. clock = time.time
  2623. if min_version is None:
  2624. min_version = DEFAULT_SIGNED_VALUE_MIN_VERSION
  2625. if min_version > 2:
  2626. raise ValueError("Unsupported min_version %d" % min_version)
  2627. if not value:
  2628. return None
  2629. value = utf8(value)
  2630. version = _get_version(value)
  2631. if version < min_version:
  2632. return None
  2633. if version == 1:
  2634. return _decode_signed_value_v1(secret, name, value,
  2635. max_age_days, clock)
  2636. elif version == 2:
  2637. return _decode_signed_value_v2(secret, name, value,
  2638. max_age_days, clock)
  2639. else:
  2640. return None
  2641. def _decode_signed_value_v1(secret, name, value, max_age_days, clock):
  2642. parts = utf8(value).split(b"|")
  2643. if len(parts) != 3:
  2644. return None
  2645. signature = _create_signature_v1(secret, name, parts[0], parts[1])
  2646. if not _time_independent_equals(parts[2], signature):
  2647. gen_log.warning("Invalid cookie signature %r", value)
  2648. return None
  2649. timestamp = int(parts[1])
  2650. if timestamp < clock() - max_age_days * 86400:
  2651. gen_log.warning("Expired cookie %r", value)
  2652. return None
  2653. if timestamp > clock() + 31 * 86400:
  2654. # _cookie_signature does not hash a delimiter between the
  2655. # parts of the cookie, so an attacker could transfer trailing
  2656. # digits from the payload to the timestamp without altering the
  2657. # signature. For backwards compatibility, sanity-check timestamp
  2658. # here instead of modifying _cookie_signature.
  2659. gen_log.warning("Cookie timestamp in future; possible tampering %r",
  2660. value)
  2661. return None
  2662. if parts[1].startswith(b"0"):
  2663. gen_log.warning("Tampered cookie %r", value)
  2664. return None
  2665. try:
  2666. return base64.b64decode(parts[0])
  2667. except Exception:
  2668. return None
  2669. def _decode_fields_v2(value):
  2670. def _consume_field(s):
  2671. length, _, rest = s.partition(b':')
  2672. n = int(length)
  2673. field_value = rest[:n]
  2674. # In python 3, indexing bytes returns small integers; we must
  2675. # use a slice to get a byte string as in python 2.
  2676. if rest[n:n + 1] != b'|':
  2677. raise ValueError("malformed v2 signed value field")
  2678. rest = rest[n + 1:]
  2679. return field_value, rest
  2680. rest = value[2:] # remove version number
  2681. key_version, rest = _consume_field(rest)
  2682. timestamp, rest = _consume_field(rest)
  2683. name_field, rest = _consume_field(rest)
  2684. value_field, passed_sig = _consume_field(rest)
  2685. return int(key_version), timestamp, name_field, value_field, passed_sig
  2686. def _decode_signed_value_v2(secret, name, value, max_age_days, clock):
  2687. try:
  2688. key_version, timestamp, name_field, value_field, passed_sig = _decode_fields_v2(value)
  2689. except ValueError:
  2690. return None
  2691. signed_string = value[:-len(passed_sig)]
  2692. if isinstance(secret, dict):
  2693. try:
  2694. secret = secret[key_version]
  2695. except KeyError:
  2696. return None
  2697. expected_sig = _create_signature_v2(secret, signed_string)
  2698. if not _time_independent_equals(passed_sig, expected_sig):
  2699. return None
  2700. if name_field != utf8(name):
  2701. return None
  2702. timestamp = int(timestamp)
  2703. if timestamp < clock() - max_age_days * 86400:
  2704. # The signature has expired.
  2705. return None
  2706. try:
  2707. return base64.b64decode(value_field)
  2708. except Exception:
  2709. return None
  2710. def get_signature_key_version(value):
  2711. value = utf8(value)
  2712. version = _get_version(value)
  2713. if version < 2:
  2714. return None
  2715. try:
  2716. key_version, _, _, _, _ = _decode_fields_v2(value)
  2717. except ValueError:
  2718. return None
  2719. return key_version
  2720. def _create_signature_v1(secret, *parts):
  2721. hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
  2722. for part in parts:
  2723. hash.update(utf8(part))
  2724. return utf8(hash.hexdigest())
  2725. def _create_signature_v2(secret, s):
  2726. hash = hmac.new(utf8(secret), digestmod=hashlib.sha256)
  2727. hash.update(utf8(s))
  2728. return utf8(hash.hexdigest())
  2729. def _unquote_or_none(s):
  2730. """None-safe wrapper around url_unescape to handle unamteched optional
  2731. groups correctly.
  2732. Note that args are passed as bytes so the handler can decide what
  2733. encoding to use.
  2734. """
  2735. if s is None:
  2736. return s
  2737. return escape.url_unescape(s, encoding=None, plus=False)