/testing/mochitest/pywebsocket/standalone.py

https://bitbucket.org/MeeGoAdmin/mozilla-central/ · Python · 484 lines · 320 code · 43 blank · 121 comment · 35 complexity · d98ab811eecdc625421791f6bbc34191 MD5 · raw file

  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2011, Google Inc.
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. #
  10. # * Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # * Redistributions in binary form must reproduce the above
  13. # copyright notice, this list of conditions and the following disclaimer
  14. # in the documentation and/or other materials provided with the
  15. # distribution.
  16. # * Neither the name of Google Inc. nor the names of its
  17. # contributors may be used to endorse or promote products derived from
  18. # this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """Standalone WebSocket server.
  32. Use this server to run mod_pywebsocket without Apache HTTP Server.
  33. Usage:
  34. python standalone.py [-p <ws_port>] [-w <websock_handlers>]
  35. [-s <scan_dir>]
  36. [-d <document_root>]
  37. [-m <websock_handlers_map_file>]
  38. ... for other options, see _main below ...
  39. <ws_port> is the port number to use for ws:// connection.
  40. <document_root> is the path to the root directory of HTML files.
  41. <websock_handlers> is the path to the root directory of WebSocket handlers.
  42. See __init__.py for details of <websock_handlers> and how to write WebSocket
  43. handlers. If this path is relative, <document_root> is used as the base.
  44. <scan_dir> is a path under the root directory. If specified, only the handlers
  45. under scan_dir are scanned. This is useful in saving scan time.
  46. Note:
  47. This server is derived from SocketServer.ThreadingMixIn. Hence a thread is
  48. used for each request.
  49. SECURITY WARNING: This uses CGIHTTPServer and CGIHTTPServer is not secure.
  50. It may execute arbitrary Python code or external programs. It should not be
  51. used outside a firewall.
  52. """
  53. import BaseHTTPServer
  54. import CGIHTTPServer
  55. import SimpleHTTPServer
  56. import SocketServer
  57. import logging
  58. import logging.handlers
  59. import optparse
  60. import os
  61. import re
  62. import socket
  63. import sys
  64. _HAS_OPEN_SSL = False
  65. try:
  66. import OpenSSL.SSL
  67. _HAS_OPEN_SSL = True
  68. except ImportError:
  69. pass
  70. from mod_pywebsocket import common
  71. from mod_pywebsocket import dispatch
  72. from mod_pywebsocket import handshake
  73. from mod_pywebsocket import memorizingfile
  74. from mod_pywebsocket import util
  75. _DEFAULT_LOG_MAX_BYTES = 1024 * 256
  76. _DEFAULT_LOG_BACKUP_COUNT = 5
  77. _DEFAULT_REQUEST_QUEUE_SIZE = 128
  78. # 1024 is practically large enough to contain WebSocket handshake lines.
  79. _MAX_MEMORIZED_LINES = 1024
  80. def _print_warnings_if_any(dispatcher):
  81. warnings = dispatcher.source_warnings()
  82. if warnings:
  83. for warning in warnings:
  84. logging.warning('mod_pywebsocket: %s' % warning)
  85. class _StandaloneConnection(object):
  86. """Mimic mod_python mp_conn."""
  87. def __init__(self, request_handler):
  88. """Construct an instance.
  89. Args:
  90. request_handler: A WebSocketRequestHandler instance.
  91. """
  92. self._request_handler = request_handler
  93. def get_local_addr(self):
  94. """Getter to mimic mp_conn.local_addr."""
  95. return (self._request_handler.server.server_name,
  96. self._request_handler.server.server_port)
  97. local_addr = property(get_local_addr)
  98. def get_remote_addr(self):
  99. """Getter to mimic mp_conn.remote_addr.
  100. Setting the property in __init__ won't work because the request
  101. handler is not initialized yet there."""
  102. return self._request_handler.client_address
  103. remote_addr = property(get_remote_addr)
  104. def write(self, data):
  105. """Mimic mp_conn.write()."""
  106. return self._request_handler.wfile.write(data)
  107. def read(self, length):
  108. """Mimic mp_conn.read()."""
  109. return self._request_handler.rfile.read(length)
  110. def get_memorized_lines(self):
  111. """Get memorized lines."""
  112. return self._request_handler.rfile.get_memorized_lines()
  113. def setblocking(self, blocking):
  114. self._request_handler.rfile._file._sock.setblocking(0)
  115. class _StandaloneRequest(object):
  116. """Mimic mod_python request."""
  117. def __init__(self, request_handler, use_tls):
  118. """Construct an instance.
  119. Args:
  120. request_handler: A WebSocketRequestHandler instance.
  121. """
  122. self._request_handler = request_handler
  123. self.connection = _StandaloneConnection(request_handler)
  124. self._use_tls = use_tls
  125. def get_uri(self):
  126. """Getter to mimic request.uri."""
  127. return self._request_handler.path
  128. uri = property(get_uri)
  129. def get_method(self):
  130. """Getter to mimic request.method."""
  131. return self._request_handler.command
  132. method = property(get_method)
  133. def get_headers_in(self):
  134. """Getter to mimic request.headers_in."""
  135. return self._request_handler.headers
  136. headers_in = property(get_headers_in)
  137. def is_https(self):
  138. """Mimic request.is_https()."""
  139. return self._use_tls
  140. class WebSocketServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
  141. """HTTPServer specialized for WebSocket."""
  142. daemon_threads = True
  143. allow_reuse_address = True
  144. def __init__(self, server_address, RequestHandlerClass):
  145. """Override SocketServer.TCPServer.__init__ to set SSL enabled socket
  146. object to self.socket before server_bind and server_activate, if
  147. necessary.
  148. """
  149. SocketServer.BaseServer.__init__(
  150. self, server_address, RequestHandlerClass)
  151. self.socket = self._create_socket()
  152. self.server_bind()
  153. self.server_activate()
  154. def _create_socket(self):
  155. socket_ = socket.socket(self.address_family, self.socket_type)
  156. if WebSocketServer.options.use_tls:
  157. ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
  158. ctx.use_privatekey_file(WebSocketServer.options.private_key)
  159. ctx.use_certificate_file(WebSocketServer.options.certificate)
  160. socket_ = OpenSSL.SSL.Connection(ctx, socket_)
  161. return socket_
  162. def handle_error(self, rquest, client_address):
  163. """Override SocketServer.handle_error."""
  164. logging.error(
  165. ('Exception in processing request from: %r' % (client_address,)) +
  166. '\n' + util.get_stack_trace())
  167. # Note: client_address is a tuple. To match it against %r, we need the
  168. # trailing comma.
  169. class WebSocketRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
  170. """CGIHTTPRequestHandler specialized for WebSocket."""
  171. def setup(self):
  172. """Override SocketServer.StreamRequestHandler.setup to wrap rfile with
  173. MemorizingFile.
  174. """
  175. # Call superclass's setup to prepare rfile, wfile, etc. See setup
  176. # definition on the root class SocketServer.StreamRequestHandler to
  177. # understand what this does.
  178. CGIHTTPServer.CGIHTTPRequestHandler.setup(self)
  179. self.rfile = memorizingfile.MemorizingFile(
  180. self.rfile,
  181. max_memorized_lines=_MAX_MEMORIZED_LINES)
  182. def __init__(self, *args, **keywords):
  183. self._request = _StandaloneRequest(
  184. self, WebSocketRequestHandler.options.use_tls)
  185. self._dispatcher = WebSocketRequestHandler.options.dispatcher
  186. self._print_warnings_if_any()
  187. self._handshaker = handshake.Handshaker(
  188. self._request, self._dispatcher,
  189. allowDraft75=WebSocketRequestHandler.options.allow_draft75,
  190. strict=WebSocketRequestHandler.options.strict)
  191. CGIHTTPServer.CGIHTTPRequestHandler.__init__(
  192. self, *args, **keywords)
  193. def _print_warnings_if_any(self):
  194. warnings = self._dispatcher.source_warnings()
  195. if warnings:
  196. for warning in warnings:
  197. logging.warning('mod_pywebsocket: %s' % warning)
  198. def parse_request(self):
  199. """Override BaseHTTPServer.BaseHTTPRequestHandler.parse_request.
  200. Return True to continue processing for HTTP(S), False otherwise.
  201. """
  202. result = CGIHTTPServer.CGIHTTPRequestHandler.parse_request(self)
  203. if result:
  204. try:
  205. self._handshaker.do_handshake()
  206. try:
  207. self._dispatcher.transfer_data(self._request)
  208. except Exception, e:
  209. # Catch exception in transfer_data.
  210. # In this case, handshake has been successful, so just log
  211. # the exception and return False.
  212. logging.info('mod_pywebsocket: %s' % e)
  213. logging.info(
  214. 'mod_pywebsocket: %s' % util.get_stack_trace())
  215. return False
  216. except handshake.HandshakeError, e:
  217. # Handshake for ws(s) failed. Assume http(s).
  218. logging.info('mod_pywebsocket: %s' % e)
  219. return True
  220. except dispatch.DispatchError, e:
  221. logging.warning('mod_pywebsocket: %s' % e)
  222. return False
  223. except Exception, e:
  224. logging.warning('mod_pywebsocket: %s' % e)
  225. logging.warning('mod_pywebsocket: %s' % util.get_stack_trace())
  226. return False
  227. return result
  228. def log_request(self, code='-', size='-'):
  229. """Override BaseHTTPServer.log_request."""
  230. logging.info('"%s" %s %s',
  231. self.requestline, str(code), str(size))
  232. def log_error(self, *args):
  233. """Override BaseHTTPServer.log_error."""
  234. # Despite the name, this method is for warnings than for errors.
  235. # For example, HTTP status code is logged by this method.
  236. logging.warn('%s - %s' % (self.address_string(), (args[0] % args[1:])))
  237. def is_cgi(self):
  238. """Test whether self.path corresponds to a CGI script.
  239. Add extra check that self.path doesn't contains ..
  240. Also check if the file is a executable file or not.
  241. If the file is not executable, it is handled as static file or dir
  242. rather than a CGI script.
  243. """
  244. if CGIHTTPServer.CGIHTTPRequestHandler.is_cgi(self):
  245. if '..' in self.path:
  246. return False
  247. # strip query parameter from request path
  248. resource_name = self.path.split('?', 2)[0]
  249. # convert resource_name into real path name in filesystem.
  250. scriptfile = self.translate_path(resource_name)
  251. if not os.path.isfile(scriptfile):
  252. return False
  253. if not self.is_executable(scriptfile):
  254. return False
  255. return True
  256. return False
  257. def _configure_logging(options):
  258. logger = logging.getLogger()
  259. logger.setLevel(logging.getLevelName(options.log_level.upper()))
  260. if options.log_file:
  261. handler = logging.handlers.RotatingFileHandler(
  262. options.log_file, 'a', options.log_max, options.log_count)
  263. else:
  264. handler = logging.StreamHandler()
  265. formatter = logging.Formatter(
  266. '[%(asctime)s] [%(levelname)s] %(name)s: %(message)s')
  267. handler.setFormatter(formatter)
  268. logger.addHandler(handler)
  269. def _alias_handlers(dispatcher, websock_handlers_map_file):
  270. """Set aliases specified in websock_handler_map_file in dispatcher.
  271. Args:
  272. dispatcher: dispatch.Dispatcher instance
  273. websock_handler_map_file: alias map file
  274. """
  275. fp = open(websock_handlers_map_file)
  276. try:
  277. for line in fp:
  278. if line[0] == '#' or line.isspace():
  279. continue
  280. m = re.match('(\S+)\s+(\S+)', line)
  281. if not m:
  282. logging.warning('Wrong format in map file:' + line)
  283. continue
  284. try:
  285. dispatcher.add_resource_path_alias(
  286. m.group(1), m.group(2))
  287. except dispatch.DispatchError, e:
  288. logging.error(str(e))
  289. finally:
  290. fp.close()
  291. def _main():
  292. parser = optparse.OptionParser()
  293. parser.add_option('-H', '--server-host', '--server_host',
  294. dest='server_host',
  295. default='',
  296. help='server hostname to listen to')
  297. parser.add_option('-p', '--port', dest='port', type='int',
  298. default=common.DEFAULT_WEB_SOCKET_PORT,
  299. help='port to listen to')
  300. parser.add_option('-w', '--websock-handlers', '--websock_handlers',
  301. dest='websock_handlers',
  302. default='.',
  303. help='WebSocket handlers root directory.')
  304. parser.add_option('-m', '--websock-handlers-map-file',
  305. '--websock_handlers_map_file',
  306. dest='websock_handlers_map_file',
  307. default=None,
  308. help=('WebSocket handlers map file. '
  309. 'Each line consists of alias_resource_path and '
  310. 'existing_resource_path, separated by spaces.'))
  311. parser.add_option('-s', '--scan-dir', '--scan_dir', dest='scan_dir',
  312. default=None,
  313. help=('WebSocket handlers scan directory. '
  314. 'Must be a directory under websock_handlers.'))
  315. parser.add_option('-d', '--document-root', '--document_root',
  316. dest='document_root', default='.',
  317. help='Document root directory.')
  318. parser.add_option('-x', '--cgi-paths', '--cgi_paths', dest='cgi_paths',
  319. default=None,
  320. help=('CGI paths relative to document_root.'
  321. 'Comma-separated. (e.g -x /cgi,/htbin) '
  322. 'Files under document_root/cgi_path are handled '
  323. 'as CGI programs. Must be executable.'))
  324. parser.add_option('-t', '--tls', dest='use_tls', action='store_true',
  325. default=False, help='use TLS (wss://)')
  326. parser.add_option('-k', '--private-key', '--private_key',
  327. dest='private_key',
  328. default='', help='TLS private key file.')
  329. parser.add_option('-c', '--certificate', dest='certificate',
  330. default='', help='TLS certificate file.')
  331. parser.add_option('-l', '--log-file', '--log_file', dest='log_file',
  332. default='', help='Log file.')
  333. parser.add_option('--log-level', '--log_level', type='choice',
  334. dest='log_level', default='warn',
  335. choices=['debug', 'info', 'warning', 'warn', 'error',
  336. 'critical'],
  337. help='Log level.')
  338. parser.add_option('--log-max', '--log_max', dest='log_max', type='int',
  339. default=_DEFAULT_LOG_MAX_BYTES,
  340. help='Log maximum bytes')
  341. parser.add_option('--log-count', '--log_count', dest='log_count',
  342. type='int', default=_DEFAULT_LOG_BACKUP_COUNT,
  343. help='Log backup count')
  344. parser.add_option('--allow-draft75', dest='allow_draft75',
  345. action='store_true', default=False,
  346. help='Allow draft 75 handshake')
  347. parser.add_option('--strict', dest='strict', action='store_true',
  348. default=False, help='Strictly check handshake request')
  349. parser.add_option('-q', '--queue', dest='request_queue_size', type='int',
  350. default=_DEFAULT_REQUEST_QUEUE_SIZE,
  351. help='request queue size')
  352. options = parser.parse_args()[0]
  353. os.chdir(options.document_root)
  354. _configure_logging(options)
  355. SocketServer.TCPServer.request_queue_size = options.request_queue_size
  356. CGIHTTPServer.CGIHTTPRequestHandler.cgi_directories = []
  357. if options.cgi_paths:
  358. CGIHTTPServer.CGIHTTPRequestHandler.cgi_directories = \
  359. options.cgi_paths.split(',')
  360. if sys.platform in ('cygwin', 'win32'):
  361. cygwin_path = None
  362. # For Win32 Python, it is expected that CYGWIN_PATH
  363. # is set to a directory of cygwin binaries.
  364. # For example, websocket_server.py in Chromium sets CYGWIN_PATH to
  365. # full path of third_party/cygwin/bin.
  366. if 'CYGWIN_PATH' in os.environ:
  367. cygwin_path = os.environ['CYGWIN_PATH']
  368. util.wrap_popen3_for_win(cygwin_path)
  369. def __check_script(scriptpath):
  370. return util.get_script_interp(scriptpath, cygwin_path)
  371. CGIHTTPServer.executable = __check_script
  372. if options.use_tls:
  373. if not _HAS_OPEN_SSL:
  374. logging.critical('To use TLS, install pyOpenSSL.')
  375. sys.exit(1)
  376. if not options.private_key or not options.certificate:
  377. logging.critical(
  378. 'To use TLS, specify private_key and certificate.')
  379. sys.exit(1)
  380. if not options.scan_dir:
  381. options.scan_dir = options.websock_handlers
  382. try:
  383. # Share a Dispatcher among request handlers to save time for
  384. # instantiation. Dispatcher can be shared because it is thread-safe.
  385. options.dispatcher = dispatch.Dispatcher(options.websock_handlers,
  386. options.scan_dir)
  387. if options.websock_handlers_map_file:
  388. _alias_handlers(options.dispatcher,
  389. options.websock_handlers_map_file)
  390. _print_warnings_if_any(options.dispatcher)
  391. WebSocketRequestHandler.options = options
  392. WebSocketServer.options = options
  393. server = WebSocketServer((options.server_host, options.port),
  394. WebSocketRequestHandler)
  395. server.serve_forever()
  396. except Exception, e:
  397. logging.critical('mod_pywebsocket: %s' % e)
  398. logging.critical('mod_pywebsocket: %s' % util.get_stack_trace())
  399. sys.exit(1)
  400. if __name__ == '__main__':
  401. _main()
  402. # vi:sts=4 sw=4 et