PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py

https://gitlab.com/imxiangpeng/qtwebkit
Python | 1139 lines | 1080 code | 2 blank | 57 comment | 0 complexity | b88808ba9a5be2ad5cbc3f36fb0963e4 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, LGPL-3.0, BSD-3-Clause, AGPL-3.0
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2012, 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 file to launch pywebsocket without Apache HTTP Server.
  33. BASIC USAGE
  34. Go to the src directory and run
  35. $ python mod_pywebsocket/standalone.py [-p <ws_port>]
  36. [-w <websock_handlers>]
  37. [-d <document_root>]
  38. <ws_port> is the port number to use for ws:// connection.
  39. <document_root> is the path to the root directory of HTML files.
  40. <websock_handlers> is the path to the root directory of WebSocket handlers.
  41. If not specified, <document_root> will be used. See __init__.py (or
  42. run $ pydoc mod_pywebsocket) for how to write WebSocket handlers.
  43. For more detail and other options, run
  44. $ python mod_pywebsocket/standalone.py --help
  45. or see _build_option_parser method below.
  46. For trouble shooting, adding "--log_level debug" might help you.
  47. TRY DEMO
  48. Go to the src directory and run
  49. $ python standalone.py -d example
  50. to launch pywebsocket with the sample handler and html on port 80. Open
  51. http://localhost/console.html, click the connect button, type something into
  52. the text box next to the send button and click the send button. If everything
  53. is working, you'll see the message you typed echoed by the server.
  54. SUPPORTING TLS
  55. To support TLS, run standalone.py with -t, -k, and -c options.
  56. Note that when ssl module is used and the key/cert location is incorrect,
  57. TLS connection silently fails while pyOpenSSL fails on startup.
  58. SUPPORTING CLIENT AUTHENTICATION
  59. To support client authentication with TLS, run standalone.py with -t, -k, -c,
  60. and --tls-client-auth, and --tls-client-ca options.
  61. E.g., $./standalone.py -d ../example -p 10443 -t -c ../test/cert/cert.pem -k
  62. ../test/cert/key.pem --tls-client-auth --tls-client-ca=../test/cert/cacert.pem
  63. CONFIGURATION FILE
  64. You can also write a configuration file and use it by specifying the path to
  65. the configuration file by --config option. Please write a configuration file
  66. following the documentation of the Python ConfigParser library. Name of each
  67. entry must be the long version argument name. E.g. to set log level to debug,
  68. add the following line:
  69. log_level=debug
  70. For options which doesn't take value, please add some fake value. E.g. for
  71. --tls option, add the following line:
  72. tls=True
  73. Note that tls will be enabled even if you write tls=False as the value part is
  74. fake.
  75. When both a command line argument and a configuration file entry are set for
  76. the same configuration item, the command line value will override one in the
  77. configuration file.
  78. THREADING
  79. This server is derived from SocketServer.ThreadingMixIn. Hence a thread is
  80. used for each request.
  81. SECURITY WARNING
  82. This uses CGIHTTPServer and CGIHTTPServer is not secure.
  83. It may execute arbitrary Python code or external programs. It should not be
  84. used outside a firewall.
  85. """
  86. import BaseHTTPServer
  87. import CGIHTTPServer
  88. import SimpleHTTPServer
  89. import SocketServer
  90. import ConfigParser
  91. import base64
  92. import httplib
  93. import logging
  94. import logging.handlers
  95. import optparse
  96. import os
  97. import re
  98. import select
  99. import socket
  100. import sys
  101. import threading
  102. import time
  103. from mod_pywebsocket import common
  104. from mod_pywebsocket import dispatch
  105. from mod_pywebsocket import handshake
  106. from mod_pywebsocket import http_header_util
  107. from mod_pywebsocket import memorizingfile
  108. from mod_pywebsocket import util
  109. _DEFAULT_LOG_MAX_BYTES = 1024 * 256
  110. _DEFAULT_LOG_BACKUP_COUNT = 5
  111. _DEFAULT_REQUEST_QUEUE_SIZE = 128
  112. # 1024 is practically large enough to contain WebSocket handshake lines.
  113. _MAX_MEMORIZED_LINES = 1024
  114. # Constants for the --tls_module flag.
  115. _TLS_BY_STANDARD_MODULE = 'ssl'
  116. _TLS_BY_PYOPENSSL = 'pyopenssl'
  117. class _StandaloneConnection(object):
  118. """Mimic mod_python mp_conn."""
  119. def __init__(self, request_handler):
  120. """Construct an instance.
  121. Args:
  122. request_handler: A WebSocketRequestHandler instance.
  123. """
  124. self._request_handler = request_handler
  125. def get_local_addr(self):
  126. """Getter to mimic mp_conn.local_addr."""
  127. return (self._request_handler.server.server_name,
  128. self._request_handler.server.server_port)
  129. local_addr = property(get_local_addr)
  130. def get_remote_addr(self):
  131. """Getter to mimic mp_conn.remote_addr.
  132. Setting the property in __init__ won't work because the request
  133. handler is not initialized yet there."""
  134. return self._request_handler.client_address
  135. remote_addr = property(get_remote_addr)
  136. def write(self, data):
  137. """Mimic mp_conn.write()."""
  138. return self._request_handler.wfile.write(data)
  139. def read(self, length):
  140. """Mimic mp_conn.read()."""
  141. return self._request_handler.rfile.read(length)
  142. def get_memorized_lines(self):
  143. """Get memorized lines."""
  144. return self._request_handler.rfile.get_memorized_lines()
  145. class _StandaloneRequest(object):
  146. """Mimic mod_python request."""
  147. def __init__(self, request_handler, use_tls):
  148. """Construct an instance.
  149. Args:
  150. request_handler: A WebSocketRequestHandler instance.
  151. """
  152. self._logger = util.get_class_logger(self)
  153. self._request_handler = request_handler
  154. self.connection = _StandaloneConnection(request_handler)
  155. self._use_tls = use_tls
  156. self.headers_in = request_handler.headers
  157. def get_uri(self):
  158. """Getter to mimic request.uri.
  159. This method returns the raw data at the Request-URI part of the
  160. Request-Line, while the uri method on the request object of mod_python
  161. returns the path portion after parsing the raw data. This behavior is
  162. kept for compatibility.
  163. """
  164. return self._request_handler.path
  165. uri = property(get_uri)
  166. def get_unparsed_uri(self):
  167. """Getter to mimic request.unparsed_uri."""
  168. return self._request_handler.path
  169. unparsed_uri = property(get_unparsed_uri)
  170. def get_method(self):
  171. """Getter to mimic request.method."""
  172. return self._request_handler.command
  173. method = property(get_method)
  174. def get_protocol(self):
  175. """Getter to mimic request.protocol."""
  176. return self._request_handler.request_version
  177. protocol = property(get_protocol)
  178. def is_https(self):
  179. """Mimic request.is_https()."""
  180. return self._use_tls
  181. def _import_ssl():
  182. global ssl
  183. try:
  184. import ssl
  185. return True
  186. except ImportError:
  187. return False
  188. def _import_pyopenssl():
  189. global OpenSSL
  190. try:
  191. import OpenSSL.SSL
  192. return True
  193. except ImportError:
  194. return False
  195. class _StandaloneSSLConnection(object):
  196. """A wrapper class for OpenSSL.SSL.Connection to
  197. - provide makefile method which is not supported by the class
  198. - tweak shutdown method since OpenSSL.SSL.Connection.shutdown doesn't
  199. accept the "how" argument.
  200. - convert SysCallError exceptions that its recv method may raise into a
  201. return value of '', meaning EOF. We cannot overwrite the recv method on
  202. self._connection since it's immutable.
  203. """
  204. _OVERRIDDEN_ATTRIBUTES = ['_connection', 'makefile', 'shutdown', 'recv']
  205. def __init__(self, connection):
  206. self._connection = connection
  207. def __getattribute__(self, name):
  208. if name in _StandaloneSSLConnection._OVERRIDDEN_ATTRIBUTES:
  209. return object.__getattribute__(self, name)
  210. return self._connection.__getattribute__(name)
  211. def __setattr__(self, name, value):
  212. if name in _StandaloneSSLConnection._OVERRIDDEN_ATTRIBUTES:
  213. return object.__setattr__(self, name, value)
  214. return self._connection.__setattr__(name, value)
  215. def makefile(self, mode='r', bufsize=-1):
  216. return socket._fileobject(self, mode, bufsize)
  217. def shutdown(self, unused_how):
  218. self._connection.shutdown()
  219. def recv(self, bufsize, flags=0):
  220. if flags != 0:
  221. raise ValueError('Non-zero flags not allowed')
  222. try:
  223. return self._connection.recv(bufsize)
  224. except OpenSSL.SSL.SysCallError, (err, message):
  225. if err == -1:
  226. # Suppress "unexpected EOF" exception. See the OpenSSL document
  227. # for SSL_get_error.
  228. return ''
  229. raise
  230. def _alias_handlers(dispatcher, websock_handlers_map_file):
  231. """Set aliases specified in websock_handler_map_file in dispatcher.
  232. Args:
  233. dispatcher: dispatch.Dispatcher instance
  234. websock_handler_map_file: alias map file
  235. """
  236. fp = open(websock_handlers_map_file)
  237. try:
  238. for line in fp:
  239. if line[0] == '#' or line.isspace():
  240. continue
  241. m = re.match('(\S+)\s+(\S+)', line)
  242. if not m:
  243. logging.warning('Wrong format in map file:' + line)
  244. continue
  245. try:
  246. dispatcher.add_resource_path_alias(
  247. m.group(1), m.group(2))
  248. except dispatch.DispatchException, e:
  249. logging.error(str(e))
  250. finally:
  251. fp.close()
  252. class WebSocketServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
  253. """HTTPServer specialized for WebSocket."""
  254. # Overrides SocketServer.ThreadingMixIn.daemon_threads
  255. daemon_threads = True
  256. # Overrides BaseHTTPServer.HTTPServer.allow_reuse_address
  257. allow_reuse_address = True
  258. def __init__(self, options):
  259. """Override SocketServer.TCPServer.__init__ to set SSL enabled
  260. socket object to self.socket before server_bind and server_activate,
  261. if necessary.
  262. """
  263. # Share a Dispatcher among request handlers to save time for
  264. # instantiation. Dispatcher can be shared because it is thread-safe.
  265. options.dispatcher = dispatch.Dispatcher(
  266. options.websock_handlers,
  267. options.scan_dir,
  268. options.allow_handlers_outside_root_dir)
  269. if options.websock_handlers_map_file:
  270. _alias_handlers(options.dispatcher,
  271. options.websock_handlers_map_file)
  272. warnings = options.dispatcher.source_warnings()
  273. if warnings:
  274. for warning in warnings:
  275. logging.warning('Warning in source loading: %s' % warning)
  276. self._logger = util.get_class_logger(self)
  277. self.request_queue_size = options.request_queue_size
  278. self.__ws_is_shut_down = threading.Event()
  279. self.__ws_serving = False
  280. SocketServer.BaseServer.__init__(
  281. self, (options.server_host, options.port), WebSocketRequestHandler)
  282. # Expose the options object to allow handler objects access it. We name
  283. # it with websocket_ prefix to avoid conflict.
  284. self.websocket_server_options = options
  285. self._create_sockets()
  286. self.server_bind()
  287. self.server_activate()
  288. def _create_sockets(self):
  289. self.server_name, self.server_port = self.server_address
  290. self._sockets = []
  291. if not self.server_name:
  292. # On platforms that doesn't support IPv6, the first bind fails.
  293. # On platforms that supports IPv6
  294. # - If it binds both IPv4 and IPv6 on call with AF_INET6, the
  295. # first bind succeeds and the second fails (we'll see 'Address
  296. # already in use' error).
  297. # - If it binds only IPv6 on call with AF_INET6, both call are
  298. # expected to succeed to listen both protocol.
  299. addrinfo_array = [
  300. (socket.AF_INET6, socket.SOCK_STREAM, '', '', ''),
  301. (socket.AF_INET, socket.SOCK_STREAM, '', '', '')]
  302. else:
  303. addrinfo_array = socket.getaddrinfo(self.server_name,
  304. self.server_port,
  305. socket.AF_UNSPEC,
  306. socket.SOCK_STREAM,
  307. socket.IPPROTO_TCP)
  308. for addrinfo in addrinfo_array:
  309. self._logger.info('Create socket on: %r', addrinfo)
  310. family, socktype, proto, canonname, sockaddr = addrinfo
  311. try:
  312. socket_ = socket.socket(family, socktype)
  313. except Exception, e:
  314. self._logger.info('Skip by failure: %r', e)
  315. continue
  316. server_options = self.websocket_server_options
  317. if server_options.use_tls:
  318. # For the case of _HAS_OPEN_SSL, we do wrapper setup after
  319. # accept.
  320. if server_options.tls_module == _TLS_BY_STANDARD_MODULE:
  321. if server_options.tls_client_auth:
  322. if server_options.tls_client_cert_optional:
  323. client_cert_ = ssl.CERT_OPTIONAL
  324. else:
  325. client_cert_ = ssl.CERT_REQUIRED
  326. else:
  327. client_cert_ = ssl.CERT_NONE
  328. socket_ = ssl.wrap_socket(socket_,
  329. keyfile=server_options.private_key,
  330. certfile=server_options.certificate,
  331. ssl_version=ssl.PROTOCOL_SSLv23,
  332. ca_certs=server_options.tls_client_ca,
  333. cert_reqs=client_cert_,
  334. do_handshake_on_connect=False)
  335. self._sockets.append((socket_, addrinfo))
  336. def server_bind(self):
  337. """Override SocketServer.TCPServer.server_bind to enable multiple
  338. sockets bind.
  339. """
  340. failed_sockets = []
  341. for socketinfo in self._sockets:
  342. socket_, addrinfo = socketinfo
  343. self._logger.info('Bind on: %r', addrinfo)
  344. if self.allow_reuse_address:
  345. socket_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  346. try:
  347. socket_.bind(self.server_address)
  348. except Exception, e:
  349. self._logger.info('Skip by failure: %r', e)
  350. socket_.close()
  351. failed_sockets.append(socketinfo)
  352. if self.server_address[1] == 0:
  353. # The operating system assigns the actual port number for port
  354. # number 0. This case, the second and later sockets should use
  355. # the same port number. Also self.server_port is rewritten
  356. # because it is exported, and will be used by external code.
  357. self.server_address = (
  358. self.server_name, socket_.getsockname()[1])
  359. self.server_port = self.server_address[1]
  360. self._logger.info('Port %r is assigned', self.server_port)
  361. for socketinfo in failed_sockets:
  362. self._sockets.remove(socketinfo)
  363. def server_activate(self):
  364. """Override SocketServer.TCPServer.server_activate to enable multiple
  365. sockets listen.
  366. """
  367. failed_sockets = []
  368. for socketinfo in self._sockets:
  369. socket_, addrinfo = socketinfo
  370. self._logger.info('Listen on: %r', addrinfo)
  371. try:
  372. socket_.listen(self.request_queue_size)
  373. except Exception, e:
  374. self._logger.info('Skip by failure: %r', e)
  375. socket_.close()
  376. failed_sockets.append(socketinfo)
  377. for socketinfo in failed_sockets:
  378. self._sockets.remove(socketinfo)
  379. if len(self._sockets) == 0:
  380. self._logger.critical(
  381. 'No sockets activated. Use info log level to see the reason.')
  382. def server_close(self):
  383. """Override SocketServer.TCPServer.server_close to enable multiple
  384. sockets close.
  385. """
  386. for socketinfo in self._sockets:
  387. socket_, addrinfo = socketinfo
  388. self._logger.info('Close on: %r', addrinfo)
  389. socket_.close()
  390. def fileno(self):
  391. """Override SocketServer.TCPServer.fileno."""
  392. self._logger.critical('Not supported: fileno')
  393. return self._sockets[0][0].fileno()
  394. def handle_error(self, request, client_address):
  395. """Override SocketServer.handle_error."""
  396. self._logger.error(
  397. 'Exception in processing request from: %r\n%s',
  398. client_address,
  399. util.get_stack_trace())
  400. # Note: client_address is a tuple.
  401. def get_request(self):
  402. """Override TCPServer.get_request to wrap OpenSSL.SSL.Connection
  403. object with _StandaloneSSLConnection to provide makefile method. We
  404. cannot substitute OpenSSL.SSL.Connection.makefile since it's readonly
  405. attribute.
  406. """
  407. accepted_socket, client_address = self.socket.accept()
  408. server_options = self.websocket_server_options
  409. if server_options.use_tls:
  410. if server_options.tls_module == _TLS_BY_STANDARD_MODULE:
  411. try:
  412. accepted_socket.do_handshake()
  413. except ssl.SSLError, e:
  414. self._logger.debug('%r', e)
  415. raise
  416. # Print cipher in use. Handshake is done on accept.
  417. self._logger.debug('Cipher: %s', accepted_socket.cipher())
  418. self._logger.debug('Client cert: %r',
  419. accepted_socket.getpeercert())
  420. elif server_options.tls_module == _TLS_BY_PYOPENSSL:
  421. # We cannot print the cipher in use. pyOpenSSL doesn't provide
  422. # any method to fetch that.
  423. ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
  424. ctx.use_privatekey_file(server_options.private_key)
  425. ctx.use_certificate_file(server_options.certificate)
  426. def default_callback(conn, cert, errnum, errdepth, ok):
  427. return ok == 1
  428. # See the OpenSSL document for SSL_CTX_set_verify.
  429. if server_options.tls_client_auth:
  430. verify_mode = OpenSSL.SSL.VERIFY_PEER
  431. if not server_options.tls_client_cert_optional:
  432. verify_mode |= OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT
  433. ctx.set_verify(verify_mode, default_callback)
  434. ctx.load_verify_locations(server_options.tls_client_ca,
  435. None)
  436. else:
  437. ctx.set_verify(OpenSSL.SSL.VERIFY_NONE, default_callback)
  438. accepted_socket = OpenSSL.SSL.Connection(ctx, accepted_socket)
  439. accepted_socket.set_accept_state()
  440. # Convert SSL related error into socket.error so that
  441. # SocketServer ignores them and keeps running.
  442. #
  443. # TODO(tyoshino): Convert all kinds of errors.
  444. try:
  445. accepted_socket.do_handshake()
  446. except OpenSSL.SSL.Error, e:
  447. # Set errno part to 1 (SSL_ERROR_SSL) like the ssl module
  448. # does.
  449. self._logger.debug('%r', e)
  450. raise socket.error(1, '%r' % e)
  451. cert = accepted_socket.get_peer_certificate()
  452. self._logger.debug('Client cert subject: %r',
  453. cert.get_subject().get_components())
  454. accepted_socket = _StandaloneSSLConnection(accepted_socket)
  455. else:
  456. raise ValueError('No TLS support module is available')
  457. return accepted_socket, client_address
  458. def serve_forever(self, poll_interval=0.5):
  459. """Override SocketServer.BaseServer.serve_forever."""
  460. self.__ws_serving = True
  461. self.__ws_is_shut_down.clear()
  462. handle_request = self.handle_request
  463. if hasattr(self, '_handle_request_noblock'):
  464. handle_request = self._handle_request_noblock
  465. else:
  466. self._logger.warning('Fallback to blocking request handler')
  467. try:
  468. while self.__ws_serving:
  469. r, w, e = select.select(
  470. [socket_[0] for socket_ in self._sockets],
  471. [], [], poll_interval)
  472. for socket_ in r:
  473. self.socket = socket_
  474. handle_request()
  475. self.socket = None
  476. finally:
  477. self.__ws_is_shut_down.set()
  478. def shutdown(self):
  479. """Override SocketServer.BaseServer.shutdown."""
  480. self.__ws_serving = False
  481. self.__ws_is_shut_down.wait()
  482. class WebSocketRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
  483. """CGIHTTPRequestHandler specialized for WebSocket."""
  484. # Use httplib.HTTPMessage instead of mimetools.Message.
  485. MessageClass = httplib.HTTPMessage
  486. def setup(self):
  487. """Override SocketServer.StreamRequestHandler.setup to wrap rfile
  488. with MemorizingFile.
  489. This method will be called by BaseRequestHandler's constructor
  490. before calling BaseHTTPRequestHandler.handle.
  491. BaseHTTPRequestHandler.handle will call
  492. BaseHTTPRequestHandler.handle_one_request and it will call
  493. WebSocketRequestHandler.parse_request.
  494. """
  495. # Call superclass's setup to prepare rfile, wfile, etc. See setup
  496. # definition on the root class SocketServer.StreamRequestHandler to
  497. # understand what this does.
  498. CGIHTTPServer.CGIHTTPRequestHandler.setup(self)
  499. self.rfile = memorizingfile.MemorizingFile(
  500. self.rfile,
  501. max_memorized_lines=_MAX_MEMORIZED_LINES)
  502. def __init__(self, request, client_address, server):
  503. self._logger = util.get_class_logger(self)
  504. self._options = server.websocket_server_options
  505. # Overrides CGIHTTPServerRequestHandler.cgi_directories.
  506. self.cgi_directories = self._options.cgi_directories
  507. # Replace CGIHTTPRequestHandler.is_executable method.
  508. if self._options.is_executable_method is not None:
  509. self.is_executable = self._options.is_executable_method
  510. # This actually calls BaseRequestHandler.__init__.
  511. CGIHTTPServer.CGIHTTPRequestHandler.__init__(
  512. self, request, client_address, server)
  513. def parse_request(self):
  514. """Override BaseHTTPServer.BaseHTTPRequestHandler.parse_request.
  515. Return True to continue processing for HTTP(S), False otherwise.
  516. See BaseHTTPRequestHandler.handle_one_request method which calls
  517. this method to understand how the return value will be handled.
  518. """
  519. # We hook parse_request method, but also call the original
  520. # CGIHTTPRequestHandler.parse_request since when we return False,
  521. # CGIHTTPRequestHandler.handle_one_request continues processing and
  522. # it needs variables set by CGIHTTPRequestHandler.parse_request.
  523. #
  524. # Variables set by this method will be also used by WebSocket request
  525. # handling (self.path, self.command, self.requestline, etc. See also
  526. # how _StandaloneRequest's members are implemented using these
  527. # attributes).
  528. if not CGIHTTPServer.CGIHTTPRequestHandler.parse_request(self):
  529. return False
  530. if self._options.use_basic_auth:
  531. auth = self.headers.getheader('Authorization')
  532. if auth != self._options.basic_auth_credential:
  533. self.send_response(401)
  534. self.send_header('WWW-Authenticate',
  535. 'Basic realm="Pywebsocket"')
  536. self.end_headers()
  537. self._logger.info('Request basic authentication')
  538. return True
  539. host, port, resource = http_header_util.parse_uri(self.path)
  540. if resource is None:
  541. self._logger.info('Invalid URI: %r', self.path)
  542. self._logger.info('Fallback to CGIHTTPRequestHandler')
  543. return True
  544. server_options = self.server.websocket_server_options
  545. if host is not None:
  546. validation_host = server_options.validation_host
  547. if validation_host is not None and host != validation_host:
  548. self._logger.info('Invalid host: %r (expected: %r)',
  549. host,
  550. validation_host)
  551. self._logger.info('Fallback to CGIHTTPRequestHandler')
  552. return True
  553. if port is not None:
  554. validation_port = server_options.validation_port
  555. if validation_port is not None and port != validation_port:
  556. self._logger.info('Invalid port: %r (expected: %r)',
  557. port,
  558. validation_port)
  559. self._logger.info('Fallback to CGIHTTPRequestHandler')
  560. return True
  561. self.path = resource
  562. request = _StandaloneRequest(self, self._options.use_tls)
  563. try:
  564. # Fallback to default http handler for request paths for which
  565. # we don't have request handlers.
  566. if not self._options.dispatcher.get_handler_suite(self.path):
  567. self._logger.info('No handler for resource: %r',
  568. self.path)
  569. self._logger.info('Fallback to CGIHTTPRequestHandler')
  570. return True
  571. except dispatch.DispatchException, e:
  572. self._logger.info('Dispatch failed for error: %s', e)
  573. self.send_error(e.status)
  574. return False
  575. # If any Exceptions without except clause setup (including
  576. # DispatchException) is raised below this point, it will be caught
  577. # and logged by WebSocketServer.
  578. try:
  579. try:
  580. handshake.do_handshake(
  581. request,
  582. self._options.dispatcher,
  583. allowDraft75=self._options.allow_draft75,
  584. strict=self._options.strict)
  585. except handshake.VersionException, e:
  586. self._logger.info('Handshake failed for version error: %s', e)
  587. self.send_response(common.HTTP_STATUS_BAD_REQUEST)
  588. self.send_header(common.SEC_WEBSOCKET_VERSION_HEADER,
  589. e.supported_versions)
  590. self.end_headers()
  591. return False
  592. except handshake.HandshakeException, e:
  593. # Handshake for ws(s) failed.
  594. self._logger.info('Handshake failed for error: %s', e)
  595. self.send_error(e.status)
  596. return False
  597. request._dispatcher = self._options.dispatcher
  598. self._options.dispatcher.transfer_data(request)
  599. except handshake.AbortedByUserException, e:
  600. self._logger.info('Aborted: %s', e)
  601. return False
  602. def log_request(self, code='-', size='-'):
  603. """Override BaseHTTPServer.log_request."""
  604. self._logger.info('"%s" %s %s',
  605. self.requestline, str(code), str(size))
  606. def log_error(self, *args):
  607. """Override BaseHTTPServer.log_error."""
  608. # Despite the name, this method is for warnings than for errors.
  609. # For example, HTTP status code is logged by this method.
  610. self._logger.warning('%s - %s',
  611. self.address_string(),
  612. args[0] % args[1:])
  613. def is_cgi(self):
  614. """Test whether self.path corresponds to a CGI script.
  615. Add extra check that self.path doesn't contains ..
  616. Also check if the file is a executable file or not.
  617. If the file is not executable, it is handled as static file or dir
  618. rather than a CGI script.
  619. """
  620. if CGIHTTPServer.CGIHTTPRequestHandler.is_cgi(self):
  621. if '..' in self.path:
  622. return False
  623. # strip query parameter from request path
  624. resource_name = self.path.split('?', 2)[0]
  625. # convert resource_name into real path name in filesystem.
  626. scriptfile = self.translate_path(resource_name)
  627. if not os.path.isfile(scriptfile):
  628. return False
  629. if not self.is_executable(scriptfile):
  630. return False
  631. return True
  632. return False
  633. def _get_logger_from_class(c):
  634. return logging.getLogger('%s.%s' % (c.__module__, c.__name__))
  635. def _configure_logging(options):
  636. logging.addLevelName(common.LOGLEVEL_FINE, 'FINE')
  637. logger = logging.getLogger()
  638. logger.setLevel(logging.getLevelName(options.log_level.upper()))
  639. if options.log_file:
  640. handler = logging.handlers.RotatingFileHandler(
  641. options.log_file, 'a', options.log_max, options.log_count)
  642. else:
  643. handler = logging.StreamHandler()
  644. formatter = logging.Formatter(
  645. '[%(asctime)s] [%(levelname)s] %(name)s: %(message)s')
  646. handler.setFormatter(formatter)
  647. logger.addHandler(handler)
  648. deflate_log_level_name = logging.getLevelName(
  649. options.deflate_log_level.upper())
  650. _get_logger_from_class(util._Deflater).setLevel(
  651. deflate_log_level_name)
  652. _get_logger_from_class(util._Inflater).setLevel(
  653. deflate_log_level_name)
  654. def _build_option_parser():
  655. parser = optparse.OptionParser()
  656. parser.add_option('--config', dest='config_file', type='string',
  657. default=None,
  658. help=('Path to configuration file. See the file comment '
  659. 'at the top of this file for the configuration '
  660. 'file format'))
  661. parser.add_option('-H', '--server-host', '--server_host',
  662. dest='server_host',
  663. default='',
  664. help='server hostname to listen to')
  665. parser.add_option('-V', '--validation-host', '--validation_host',
  666. dest='validation_host',
  667. default=None,
  668. help='server hostname to validate in absolute path.')
  669. parser.add_option('-p', '--port', dest='port', type='int',
  670. default=common.DEFAULT_WEB_SOCKET_PORT,
  671. help='port to listen to')
  672. parser.add_option('-P', '--validation-port', '--validation_port',
  673. dest='validation_port', type='int',
  674. default=None,
  675. help='server port to validate in absolute path.')
  676. parser.add_option('-w', '--websock-handlers', '--websock_handlers',
  677. dest='websock_handlers',
  678. default='.',
  679. help=('The root directory of WebSocket handler files. '
  680. 'If the path is relative, --document-root is used '
  681. 'as the base.'))
  682. parser.add_option('-m', '--websock-handlers-map-file',
  683. '--websock_handlers_map_file',
  684. dest='websock_handlers_map_file',
  685. default=None,
  686. help=('WebSocket handlers map file. '
  687. 'Each line consists of alias_resource_path and '
  688. 'existing_resource_path, separated by spaces.'))
  689. parser.add_option('-s', '--scan-dir', '--scan_dir', dest='scan_dir',
  690. default=None,
  691. help=('Must be a directory under --websock-handlers. '
  692. 'Only handlers under this directory are scanned '
  693. 'and registered to the server. '
  694. 'Useful for saving scan time when the handler '
  695. 'root directory contains lots of files that are '
  696. 'not handler file or are handler files but you '
  697. 'don\'t want them to be registered. '))
  698. parser.add_option('--allow-handlers-outside-root-dir',
  699. '--allow_handlers_outside_root_dir',
  700. dest='allow_handlers_outside_root_dir',
  701. action='store_true',
  702. default=False,
  703. help=('Scans WebSocket handlers even if their canonical '
  704. 'path is not under --websock-handlers.'))
  705. parser.add_option('-d', '--document-root', '--document_root',
  706. dest='document_root', default='.',
  707. help='Document root directory.')
  708. parser.add_option('-x', '--cgi-paths', '--cgi_paths', dest='cgi_paths',
  709. default=None,
  710. help=('CGI paths relative to document_root.'
  711. 'Comma-separated. (e.g -x /cgi,/htbin) '
  712. 'Files under document_root/cgi_path are handled '
  713. 'as CGI programs. Must be executable.'))
  714. parser.add_option('-t', '--tls', dest='use_tls', action='store_true',
  715. default=False, help='use TLS (wss://)')
  716. parser.add_option('--tls-module', '--tls_module', dest='tls_module',
  717. type='choice',
  718. choices = [_TLS_BY_STANDARD_MODULE, _TLS_BY_PYOPENSSL],
  719. help='Use ssl module if "%s" is specified. '
  720. 'Use pyOpenSSL module if "%s" is specified' %
  721. (_TLS_BY_STANDARD_MODULE, _TLS_BY_PYOPENSSL))
  722. parser.add_option('-k', '--private-key', '--private_key',
  723. dest='private_key',
  724. default='', help='TLS private key file.')
  725. parser.add_option('-c', '--certificate', dest='certificate',
  726. default='', help='TLS certificate file.')
  727. parser.add_option('--tls-client-auth', dest='tls_client_auth',
  728. action='store_true', default=False,
  729. help='Requests TLS client auth on every connection.')
  730. parser.add_option('--tls-client-cert-optional',
  731. dest='tls_client_cert_optional',
  732. action='store_true', default=False,
  733. help=('Makes client certificate optional even though '
  734. 'TLS client auth is enabled.'))
  735. parser.add_option('--tls-client-ca', dest='tls_client_ca', default='',
  736. help=('Specifies a pem file which contains a set of '
  737. 'concatenated CA certificates which are used to '
  738. 'validate certificates passed from clients'))
  739. parser.add_option('--basic-auth', dest='use_basic_auth',
  740. action='store_true', default=False,
  741. help='Requires Basic authentication.')
  742. parser.add_option('--basic-auth-credential',
  743. dest='basic_auth_credential', default='test:test',
  744. help='Specifies the credential of basic authentication '
  745. 'by username:password pair (e.g. test:test).')
  746. parser.add_option('-l', '--log-file', '--log_file', dest='log_file',
  747. default='', help='Log file.')
  748. # Custom log level:
  749. # - FINE: Prints status of each frame processing step
  750. parser.add_option('--log-level', '--log_level', type='choice',
  751. dest='log_level', default='warn',
  752. choices=['fine',
  753. 'debug', 'info', 'warning', 'warn', 'error',
  754. 'critical'],
  755. help='Log level.')
  756. parser.add_option('--deflate-log-level', '--deflate_log_level',
  757. type='choice',
  758. dest='deflate_log_level', default='warn',
  759. choices=['debug', 'info', 'warning', 'warn', 'error',
  760. 'critical'],
  761. help='Log level for _Deflater and _Inflater.')
  762. parser.add_option('--thread-monitor-interval-in-sec',
  763. '--thread_monitor_interval_in_sec',
  764. dest='thread_monitor_interval_in_sec',
  765. type='int', default=-1,
  766. help=('If positive integer is specified, run a thread '
  767. 'monitor to show the status of server threads '
  768. 'periodically in the specified inteval in '
  769. 'second. If non-positive integer is specified, '
  770. 'disable the thread monitor.'))
  771. parser.add_option('--log-max', '--log_max', dest='log_max', type='int',
  772. default=_DEFAULT_LOG_MAX_BYTES,
  773. help='Log maximum bytes')
  774. parser.add_option('--log-count', '--log_count', dest='log_count',
  775. type='int', default=_DEFAULT_LOG_BACKUP_COUNT,
  776. help='Log backup count')
  777. parser.add_option('--allow-draft75', dest='allow_draft75',
  778. action='store_true', default=False,
  779. help='Obsolete option. Ignored.')
  780. parser.add_option('--strict', dest='strict', action='store_true',
  781. default=False, help='Obsolete option. Ignored.')
  782. parser.add_option('-q', '--queue', dest='request_queue_size', type='int',
  783. default=_DEFAULT_REQUEST_QUEUE_SIZE,
  784. help='request queue size')
  785. return parser
  786. class ThreadMonitor(threading.Thread):
  787. daemon = True
  788. def __init__(self, interval_in_sec):
  789. threading.Thread.__init__(self, name='ThreadMonitor')
  790. self._logger = util.get_class_logger(self)
  791. self._interval_in_sec = interval_in_sec
  792. def run(self):
  793. while True:
  794. thread_name_list = []
  795. for thread in threading.enumerate():
  796. thread_name_list.append(thread.name)
  797. self._logger.info(
  798. "%d active threads: %s",
  799. threading.active_count(),
  800. ', '.join(thread_name_list))
  801. time.sleep(self._interval_in_sec)
  802. def _parse_args_and_config(args):
  803. parser = _build_option_parser()
  804. # First, parse options without configuration file.
  805. temporary_options, temporary_args = parser.parse_args(args=args)
  806. if temporary_args:
  807. logging.critical(
  808. 'Unrecognized positional arguments: %r', temporary_args)
  809. sys.exit(1)
  810. if temporary_options.config_file:
  811. try:
  812. config_fp = open(temporary_options.config_file, 'r')
  813. except IOError, e:
  814. logging.critical(
  815. 'Failed to open configuration file %r: %r',
  816. temporary_options.config_file,
  817. e)
  818. sys.exit(1)
  819. config_parser = ConfigParser.SafeConfigParser()
  820. config_parser.readfp(config_fp)
  821. config_fp.close()
  822. args_from_config = []
  823. for name, value in config_parser.items('pywebsocket'):
  824. args_from_config.append('--' + name)
  825. args_from_config.append(value)
  826. if args is None:
  827. args = args_from_config
  828. else:
  829. args = args_from_config + args
  830. return parser.parse_args(args=args)
  831. else:
  832. return temporary_options, temporary_args
  833. def _main(args=None):
  834. """You can call this function from your own program, but please note that
  835. this function has some side-effects that might affect your program. For
  836. example, util.wrap_popen3_for_win use in this method replaces implementation
  837. of os.popen3.
  838. """
  839. options, args = _parse_args_and_config(args=args)
  840. os.chdir(options.document_root)
  841. _configure_logging(options)
  842. if options.allow_draft75:
  843. logging.warning('--allow_draft75 option is obsolete.')
  844. if options.strict:
  845. logging.warning('--strict option is obsolete.')
  846. # TODO(tyoshino): Clean up initialization of CGI related values. Move some
  847. # of code here to WebSocketRequestHandler class if it's better.
  848. options.cgi_directories = []
  849. options.is_executable_method = None
  850. if options.cgi_paths:
  851. options.cgi_directories = options.cgi_paths.split(',')
  852. if sys.platform in ('cygwin', 'win32'):
  853. cygwin_path = None
  854. # For Win32 Python, it is expected that CYGWIN_PATH
  855. # is set to a directory of cygwin binaries.
  856. # For example, websocket_server.py in Chromium sets CYGWIN_PATH to
  857. # full path of third_party/cygwin/bin.
  858. if 'CYGWIN_PATH' in os.environ:
  859. cygwin_path = os.environ['CYGWIN_PATH']
  860. util.wrap_popen3_for_win(cygwin_path)
  861. def __check_script(scriptpath):
  862. return util.get_script_interp(scriptpath, cygwin_path)
  863. options.is_executable_method = __check_script
  864. if options.use_tls:
  865. if options.tls_module is None:
  866. if _import_ssl():
  867. options.tls_module = _TLS_BY_STANDARD_MODULE
  868. logging.debug('Using ssl module')
  869. elif _import_pyopenssl():
  870. options.tls_module = _TLS_BY_PYOPENSSL
  871. logging.debug('Using pyOpenSSL module')
  872. else:
  873. logging.critical(
  874. 'TLS support requires ssl or pyOpenSSL module.')
  875. sys.exit(1)
  876. elif options.tls_module == _TLS_BY_STANDARD_MODULE:
  877. if not _import_ssl():
  878. logging.critical('ssl module is not available')
  879. sys.exit(1)
  880. elif options.tls_module == _TLS_BY_PYOPENSSL:
  881. if not _import_pyopenssl():
  882. logging.critical('pyOpenSSL module is not available')
  883. sys.exit(1)
  884. else:
  885. logging.critical('Invalid --tls-module option: %r',
  886. options.tls_module)
  887. sys.exit(1)
  888. if not options.private_key or not options.certificate:
  889. logging.critical(
  890. 'To use TLS, specify private_key and certificate.')
  891. sys.exit(1)
  892. if (options.tls_client_cert_optional and
  893. not options.tls_client_auth):
  894. logging.critical('Client authentication must be enabled to '
  895. 'specify tls_client_cert_optional')
  896. sys.exit(1)
  897. else:
  898. if options.tls_module is not None:
  899. logging.critical('Use --tls-module option only together with '
  900. '--use-tls option.')
  901. sys.exit(1)
  902. if options.tls_client_auth:
  903. logging.critical('TLS must be enabled for client authentication.')
  904. sys.exit(1)
  905. if options.tls_client_cert_optional:
  906. logging.critical('TLS must be enabled for client authentication.')
  907. sys.exit(1)
  908. if not options.scan_dir:
  909. options.scan_dir = options.websock_handlers
  910. if options.use_basic_auth:
  911. options.basic_auth_credential = 'Basic ' + base64.b64encode(
  912. options.basic_auth_credential)
  913. try:
  914. if options.thread_monitor_interval_in_sec > 0:
  915. # Run a thread monitor to show the status of server threads for
  916. # debugging.
  917. ThreadMonitor(options.thread_monitor_interval_in_sec).start()
  918. server = WebSocketServer(options)
  919. server.serve_forever()
  920. except Exception, e:
  921. logging.critical('mod_pywebsocket: %s' % e)
  922. logging.critical('mod_pywebsocket: %s' % util.get_stack_trace())
  923. sys.exit(1)
  924. if __name__ == '__main__':
  925. _main(sys.argv[1:])
  926. # vi:sts=4 sw=4 et