headerparserhandler.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # Copyright 2011, Google Inc.
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above
  11. # copyright notice, this list of conditions and the following disclaimer
  12. # in the documentation and/or other materials provided with the
  13. # distribution.
  14. # * Neither the name of Google Inc. nor the names of its
  15. # contributors may be used to endorse or promote products derived from
  16. # this software without specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. """PythonHeaderParserHandler for mod_pywebsocket.
  30. Apache HTTP Server and mod_python must be configured such that this
  31. function is called to handle WebSocket request.
  32. """
  33. import logging
  34. from mod_python import apache
  35. from mod_pywebsocket import common
  36. from mod_pywebsocket import dispatch
  37. from mod_pywebsocket import handshake
  38. from mod_pywebsocket import util
  39. # PythonOption to specify the handler root directory.
  40. _PYOPT_HANDLER_ROOT = 'mod_pywebsocket.handler_root'
  41. # PythonOption to specify the handler scan directory.
  42. # This must be a directory under the root directory.
  43. # The default is the root directory.
  44. _PYOPT_HANDLER_SCAN = 'mod_pywebsocket.handler_scan'
  45. # PythonOption to allow handlers whose canonical path is
  46. # not under the root directory. It's disallowed by default.
  47. # Set this option with value of 'yes' to allow.
  48. _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT = (
  49. 'mod_pywebsocket.allow_handlers_outside_root_dir')
  50. # Map from values to their meanings. 'Yes' and 'No' are allowed just for
  51. # compatibility.
  52. _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT_DEFINITION = {
  53. 'off': False, 'no': False, 'on': True, 'yes': True}
  54. # (Obsolete option. Ignored.)
  55. # PythonOption to specify to allow handshake defined in Hixie 75 version
  56. # protocol. The default is None (Off)
  57. _PYOPT_ALLOW_DRAFT75 = 'mod_pywebsocket.allow_draft75'
  58. # Map from values to their meanings.
  59. _PYOPT_ALLOW_DRAFT75_DEFINITION = {'off': False, 'on': True}
  60. class ApacheLogHandler(logging.Handler):
  61. """Wrapper logging.Handler to emit log message to apache's error.log."""
  62. _LEVELS = {
  63. logging.DEBUG: apache.APLOG_DEBUG,
  64. logging.INFO: apache.APLOG_INFO,
  65. logging.WARNING: apache.APLOG_WARNING,
  66. logging.ERROR: apache.APLOG_ERR,
  67. logging.CRITICAL: apache.APLOG_CRIT,
  68. }
  69. def __init__(self, request=None):
  70. logging.Handler.__init__(self)
  71. self._log_error = apache.log_error
  72. if request is not None:
  73. self._log_error = request.log_error
  74. # Time and level will be printed by Apache.
  75. self._formatter = logging.Formatter('%(name)s: %(message)s')
  76. def emit(self, record):
  77. apache_level = apache.APLOG_DEBUG
  78. if record.levelno in ApacheLogHandler._LEVELS:
  79. apache_level = ApacheLogHandler._LEVELS[record.levelno]
  80. msg = self._formatter.format(record)
  81. # "server" parameter must be passed to have "level" parameter work.
  82. # If only "level" parameter is passed, nothing shows up on Apache's
  83. # log. However, at this point, we cannot get the server object of the
  84. # virtual host which will process WebSocket requests. The only server
  85. # object we can get here is apache.main_server. But Wherever (server
  86. # configuration context or virtual host context) we put
  87. # PythonHeaderParserHandler directive, apache.main_server just points
  88. # the main server instance (not any of virtual server instance). Then,
  89. # Apache follows LogLevel directive in the server configuration context
  90. # to filter logs. So, we need to specify LogLevel in the server
  91. # configuration context. Even if we specify "LogLevel debug" in the
  92. # virtual host context which actually handles WebSocket connections,
  93. # DEBUG level logs never show up unless "LogLevel debug" is specified
  94. # in the server configuration context.
  95. #
  96. # TODO(tyoshino): Provide logging methods on request object. When
  97. # request is mp_request object (when used together with Apache), the
  98. # methods call request.log_error indirectly. When request is
  99. # _StandaloneRequest, the methods call Python's logging facility which
  100. # we create in standalone.py.
  101. self._log_error(msg, apache_level, apache.main_server)
  102. def _configure_logging():
  103. logger = logging.getLogger()
  104. # Logs are filtered by Apache based on LogLevel directive in Apache
  105. # configuration file. We must just pass logs for all levels to
  106. # ApacheLogHandler.
  107. logger.setLevel(logging.DEBUG)
  108. logger.addHandler(ApacheLogHandler())
  109. _configure_logging()
  110. _LOGGER = logging.getLogger(__name__)
  111. def _parse_option(name, value, definition):
  112. if value is None:
  113. return False
  114. meaning = definition.get(value.lower())
  115. if meaning is None:
  116. raise Exception('Invalid value for PythonOption %s: %r' %
  117. (name, value))
  118. return meaning
  119. def _create_dispatcher():
  120. _LOGGER.info('Initializing Dispatcher')
  121. options = apache.main_server.get_options()
  122. handler_root = options.get(_PYOPT_HANDLER_ROOT, None)
  123. if not handler_root:
  124. raise Exception('PythonOption %s is not defined' % _PYOPT_HANDLER_ROOT,
  125. apache.APLOG_ERR)
  126. handler_scan = options.get(_PYOPT_HANDLER_SCAN, handler_root)
  127. allow_handlers_outside_root = _parse_option(
  128. _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT,
  129. options.get(_PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT),
  130. _PYOPT_ALLOW_HANDLERS_OUTSIDE_ROOT_DEFINITION)
  131. dispatcher = dispatch.Dispatcher(
  132. handler_root, handler_scan, allow_handlers_outside_root)
  133. for warning in dispatcher.source_warnings():
  134. apache.log_error(
  135. 'mod_pywebsocket: Warning in source loading: %s' % warning,
  136. apache.APLOG_WARNING)
  137. return dispatcher
  138. # Initialize
  139. _dispatcher = _create_dispatcher()
  140. def headerparserhandler(request):
  141. """Handle request.
  142. Args:
  143. request: mod_python request.
  144. This function is named headerparserhandler because it is the default
  145. name for a PythonHeaderParserHandler.
  146. """
  147. handshake_is_done = False
  148. try:
  149. # Fallback to default http handler for request paths for which
  150. # we don't have request handlers.
  151. if not _dispatcher.get_handler_suite(request.uri):
  152. request.log_error(
  153. 'mod_pywebsocket: No handler for resource: %r' % request.uri,
  154. apache.APLOG_INFO)
  155. request.log_error(
  156. 'mod_pywebsocket: Fallback to Apache', apache.APLOG_INFO)
  157. return apache.DECLINED
  158. except dispatch.DispatchException, e:
  159. request.log_error(
  160. 'mod_pywebsocket: Dispatch failed for error: %s' % e,
  161. apache.APLOG_INFO)
  162. if not handshake_is_done:
  163. return e.status
  164. try:
  165. allow_draft75 = _parse_option(
  166. _PYOPT_ALLOW_DRAFT75,
  167. apache.main_server.get_options().get(_PYOPT_ALLOW_DRAFT75),
  168. _PYOPT_ALLOW_DRAFT75_DEFINITION)
  169. try:
  170. handshake.do_handshake(
  171. request, _dispatcher, allowDraft75=allow_draft75)
  172. except handshake.VersionException, e:
  173. request.log_error(
  174. 'mod_pywebsocket: Handshake failed for version error: %s' % e,
  175. apache.APLOG_INFO)
  176. request.err_headers_out.add(common.SEC_WEBSOCKET_VERSION_HEADER,
  177. e.supported_versions)
  178. return apache.HTTP_BAD_REQUEST
  179. except handshake.HandshakeException, e:
  180. # Handshake for ws/wss failed.
  181. # Send http response with error status.
  182. request.log_error(
  183. 'mod_pywebsocket: Handshake failed for error: %s' % e,
  184. apache.APLOG_INFO)
  185. return e.status
  186. handshake_is_done = True
  187. request._dispatcher = _dispatcher
  188. _dispatcher.transfer_data(request)
  189. except handshake.AbortedByUserException, e:
  190. request.log_error('mod_pywebsocket: Aborted: %s' % e, apache.APLOG_INFO)
  191. except Exception, e:
  192. # DispatchException can also be thrown if something is wrong in
  193. # pywebsocket code. It's caught here, then.
  194. request.log_error('mod_pywebsocket: Exception occurred: %s\n%s' %
  195. (e, util.get_stack_trace()),
  196. apache.APLOG_ERR)
  197. # Unknown exceptions before handshake mean Apache must handle its
  198. # request with another handler.
  199. if not handshake_is_done:
  200. return apache.DECLINED
  201. # Set assbackwards to suppress response header generation by Apache.
  202. request.assbackwards = 1
  203. return apache.DONE # Return DONE such that no other handlers are invoked.
  204. # vi:sts=4 sw=4 et