fixers.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. """
  2. Fixers
  3. ======
  4. .. warning::
  5. .. deprecated:: 0.15
  6. ``ProxyFix`` has moved to :mod:`werkzeug.middleware.proxy_fix`.
  7. All other code in this module is deprecated and will be removed
  8. in version 1.0.
  9. .. versionadded:: 0.5
  10. This module includes various helpers that fix web server behavior.
  11. .. autoclass:: ProxyFix
  12. :members:
  13. .. autoclass:: CGIRootFix
  14. .. autoclass:: PathInfoFromRequestUriFix
  15. .. autoclass:: HeaderRewriterFix
  16. .. autoclass:: InternetExplorerFix
  17. :copyright: 2007 Pallets
  18. :license: BSD-3-Clause
  19. """
  20. import warnings
  21. from ..datastructures import Headers
  22. from ..datastructures import ResponseCacheControl
  23. from ..http import parse_cache_control_header
  24. from ..http import parse_options_header
  25. from ..http import parse_set_header
  26. from ..middleware.proxy_fix import ProxyFix as _ProxyFix
  27. from ..useragents import UserAgent
  28. try:
  29. from urllib.parse import unquote
  30. except ImportError:
  31. from urllib import unquote
  32. class CGIRootFix(object):
  33. """Wrap the application in this middleware if you are using FastCGI
  34. or CGI and you have problems with your app root being set to the CGI
  35. script's path instead of the path users are going to visit.
  36. :param app: the WSGI application
  37. :param app_root: Defaulting to ``'/'``, you can set this to
  38. something else if your app is mounted somewhere else.
  39. .. deprecated:: 0.15
  40. This middleware will be removed in version 1.0.
  41. .. versionchanged:: 0.9
  42. Added `app_root` parameter and renamed from
  43. ``LighttpdCGIRootFix``.
  44. """
  45. def __init__(self, app, app_root="/"):
  46. warnings.warn(
  47. "'CGIRootFix' is deprecated as of version 0.15 and will be"
  48. " removed in version 1.0.",
  49. DeprecationWarning,
  50. stacklevel=2,
  51. )
  52. self.app = app
  53. self.app_root = app_root.strip("/")
  54. def __call__(self, environ, start_response):
  55. environ["SCRIPT_NAME"] = self.app_root
  56. return self.app(environ, start_response)
  57. class LighttpdCGIRootFix(CGIRootFix):
  58. def __init__(self, *args, **kwargs):
  59. warnings.warn(
  60. "'LighttpdCGIRootFix' is renamed 'CGIRootFix'. Both will be"
  61. " removed in version 1.0.",
  62. DeprecationWarning,
  63. stacklevel=2,
  64. )
  65. super(LighttpdCGIRootFix, self).__init__(*args, **kwargs)
  66. class PathInfoFromRequestUriFix(object):
  67. """On windows environment variables are limited to the system charset
  68. which makes it impossible to store the `PATH_INFO` variable in the
  69. environment without loss of information on some systems.
  70. This is for example a problem for CGI scripts on a Windows Apache.
  71. This fixer works by recreating the `PATH_INFO` from `REQUEST_URI`,
  72. `REQUEST_URL`, or `UNENCODED_URL` (whatever is available). Thus the
  73. fix can only be applied if the webserver supports either of these
  74. variables.
  75. :param app: the WSGI application
  76. .. deprecated:: 0.15
  77. This middleware will be removed in version 1.0.
  78. """
  79. def __init__(self, app):
  80. warnings.warn(
  81. "'PathInfoFromRequestUriFix' is deprecated as of version"
  82. " 0.15 and will be removed in version 1.0.",
  83. DeprecationWarning,
  84. stacklevel=2,
  85. )
  86. self.app = app
  87. def __call__(self, environ, start_response):
  88. for key in "REQUEST_URL", "REQUEST_URI", "UNENCODED_URL":
  89. if key not in environ:
  90. continue
  91. request_uri = unquote(environ[key])
  92. script_name = unquote(environ.get("SCRIPT_NAME", ""))
  93. if request_uri.startswith(script_name):
  94. environ["PATH_INFO"] = request_uri[len(script_name) :].split("?", 1)[0]
  95. break
  96. return self.app(environ, start_response)
  97. class ProxyFix(_ProxyFix):
  98. """
  99. .. deprecated:: 0.15
  100. ``werkzeug.contrib.fixers.ProxyFix`` has moved to
  101. :mod:`werkzeug.middleware.proxy_fix`. This import will be
  102. removed in 1.0.
  103. """
  104. def __init__(self, *args, **kwargs):
  105. warnings.warn(
  106. "'werkzeug.contrib.fixers.ProxyFix' has moved to 'werkzeug"
  107. ".middleware.proxy_fix.ProxyFix'. This import is deprecated"
  108. " as of version 0.15 and will be removed in 1.0.",
  109. DeprecationWarning,
  110. stacklevel=2,
  111. )
  112. super(ProxyFix, self).__init__(*args, **kwargs)
  113. class HeaderRewriterFix(object):
  114. """This middleware can remove response headers and add others. This
  115. is for example useful to remove the `Date` header from responses if you
  116. are using a server that adds that header, no matter if it's present or
  117. not or to add `X-Powered-By` headers::
  118. app = HeaderRewriterFix(app, remove_headers=['Date'],
  119. add_headers=[('X-Powered-By', 'WSGI')])
  120. :param app: the WSGI application
  121. :param remove_headers: a sequence of header keys that should be
  122. removed.
  123. :param add_headers: a sequence of ``(key, value)`` tuples that should
  124. be added.
  125. .. deprecated:: 0.15
  126. This middleware will be removed in 1.0.
  127. """
  128. def __init__(self, app, remove_headers=None, add_headers=None):
  129. warnings.warn(
  130. "'HeaderRewriterFix' is deprecated as of version 0.15 and"
  131. " will be removed in version 1.0.",
  132. DeprecationWarning,
  133. stacklevel=2,
  134. )
  135. self.app = app
  136. self.remove_headers = set(x.lower() for x in (remove_headers or ()))
  137. self.add_headers = list(add_headers or ())
  138. def __call__(self, environ, start_response):
  139. def rewriting_start_response(status, headers, exc_info=None):
  140. new_headers = []
  141. for key, value in headers:
  142. if key.lower() not in self.remove_headers:
  143. new_headers.append((key, value))
  144. new_headers += self.add_headers
  145. return start_response(status, new_headers, exc_info)
  146. return self.app(environ, rewriting_start_response)
  147. class InternetExplorerFix(object):
  148. """This middleware fixes a couple of bugs with Microsoft Internet
  149. Explorer. Currently the following fixes are applied:
  150. - removing of `Vary` headers for unsupported mimetypes which
  151. causes troubles with caching. Can be disabled by passing
  152. ``fix_vary=False`` to the constructor.
  153. see: https://support.microsoft.com/en-us/help/824847
  154. - removes offending headers to work around caching bugs in
  155. Internet Explorer if `Content-Disposition` is set. Can be
  156. disabled by passing ``fix_attach=False`` to the constructor.
  157. If it does not detect affected Internet Explorer versions it won't touch
  158. the request / response.
  159. .. deprecated:: 0.15
  160. This middleware will be removed in 1.0.
  161. """
  162. # This code was inspired by Django fixers for the same bugs. The
  163. # fix_vary and fix_attach fixers were originally implemented in Django
  164. # by Michael Axiak and is available as part of the Django project:
  165. # https://code.djangoproject.com/ticket/4148
  166. def __init__(self, app, fix_vary=True, fix_attach=True):
  167. warnings.warn(
  168. "'InternetExplorerFix' is deprecated as of version 0.15 and"
  169. " will be removed in version 1.0.",
  170. DeprecationWarning,
  171. stacklevel=2,
  172. )
  173. self.app = app
  174. self.fix_vary = fix_vary
  175. self.fix_attach = fix_attach
  176. def fix_headers(self, environ, headers, status=None):
  177. if self.fix_vary:
  178. header = headers.get("content-type", "")
  179. mimetype, options = parse_options_header(header)
  180. if mimetype not in ("text/html", "text/plain", "text/sgml"):
  181. headers.pop("vary", None)
  182. if self.fix_attach and "content-disposition" in headers:
  183. pragma = parse_set_header(headers.get("pragma", ""))
  184. pragma.discard("no-cache")
  185. header = pragma.to_header()
  186. if not header:
  187. headers.pop("pragma", "")
  188. else:
  189. headers["Pragma"] = header
  190. header = headers.get("cache-control", "")
  191. if header:
  192. cc = parse_cache_control_header(header, cls=ResponseCacheControl)
  193. cc.no_cache = None
  194. cc.no_store = False
  195. header = cc.to_header()
  196. if not header:
  197. headers.pop("cache-control", "")
  198. else:
  199. headers["Cache-Control"] = header
  200. def run_fixed(self, environ, start_response):
  201. def fixing_start_response(status, headers, exc_info=None):
  202. headers = Headers(headers)
  203. self.fix_headers(environ, headers, status)
  204. return start_response(status, headers.to_wsgi_list(), exc_info)
  205. return self.app(environ, fixing_start_response)
  206. def __call__(self, environ, start_response):
  207. ua = UserAgent(environ)
  208. if ua.browser != "msie":
  209. return self.app(environ, start_response)
  210. return self.run_fixed(environ, start_response)