wsgi.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. import errno
  2. import os
  3. import sys
  4. import time
  5. import traceback
  6. import types
  7. import warnings
  8. import eventlet
  9. from eventlet import greenio
  10. from eventlet import support
  11. from eventlet.green import BaseHTTPServer
  12. from eventlet.green import socket
  13. import six
  14. from six.moves import urllib
  15. DEFAULT_MAX_SIMULTANEOUS_REQUESTS = 1024
  16. DEFAULT_MAX_HTTP_VERSION = 'HTTP/1.1'
  17. MAX_REQUEST_LINE = 8192
  18. MAX_HEADER_LINE = 8192
  19. MAX_TOTAL_HEADER_SIZE = 65536
  20. MINIMUM_CHUNK_SIZE = 4096
  21. # %(client_port)s is also available
  22. DEFAULT_LOG_FORMAT = ('%(client_ip)s - - [%(date_time)s] "%(request_line)s"'
  23. ' %(status_code)s %(body_length)s %(wall_seconds).6f')
  24. RESPONSE_414 = b'''HTTP/1.0 414 Request URI Too Long\r\n\
  25. Connection: close\r\n\
  26. Content-Length: 0\r\n\r\n'''
  27. is_accepting = True
  28. STATE_IDLE = 'idle'
  29. STATE_REQUEST = 'request'
  30. STATE_CLOSE = 'close'
  31. __all__ = ['server', 'format_date_time']
  32. # Weekday and month names for HTTP date/time formatting; always English!
  33. _weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  34. _monthname = [None, # Dummy so we can use 1-based month numbers
  35. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  36. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  37. def format_date_time(timestamp):
  38. """Formats a unix timestamp into an HTTP standard string."""
  39. year, month, day, hh, mm, ss, wd, _y, _z = time.gmtime(timestamp)
  40. return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
  41. _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
  42. )
  43. def addr_to_host_port(addr):
  44. host = 'unix'
  45. port = ''
  46. if isinstance(addr, tuple):
  47. host = addr[0]
  48. port = addr[1]
  49. return (host, port)
  50. # Collections of error codes to compare against. Not all attributes are set
  51. # on errno module on all platforms, so some are literals :(
  52. BAD_SOCK = set((errno.EBADF, 10053))
  53. BROKEN_SOCK = set((errno.EPIPE, errno.ECONNRESET))
  54. class ChunkReadError(ValueError):
  55. pass
  56. # special flag return value for apps
  57. class _AlreadyHandled(object):
  58. def __iter__(self):
  59. return self
  60. def next(self):
  61. raise StopIteration
  62. __next__ = next
  63. ALREADY_HANDLED = _AlreadyHandled()
  64. class Input(object):
  65. def __init__(self,
  66. rfile,
  67. content_length,
  68. sock,
  69. wfile=None,
  70. wfile_line=None,
  71. chunked_input=False):
  72. self.rfile = rfile
  73. self._sock = sock
  74. if content_length is not None:
  75. content_length = int(content_length)
  76. self.content_length = content_length
  77. self.wfile = wfile
  78. self.wfile_line = wfile_line
  79. self.position = 0
  80. self.chunked_input = chunked_input
  81. self.chunk_length = -1
  82. # (optional) headers to send with a "100 Continue" response. Set by
  83. # calling set_hundred_continue_respose_headers() on env['wsgi.input']
  84. self.hundred_continue_headers = None
  85. self.is_hundred_continue_response_sent = False
  86. # handle_one_response should give us a ref to the response state so we
  87. # know whether we can still send the 100 Continue; until then, though,
  88. # we're flying blind
  89. self.headers_sent = None
  90. def send_hundred_continue_response(self):
  91. if self.headers_sent:
  92. # To late; application has already started sending data back
  93. # to the client
  94. # TODO: maybe log a warning if self.hundred_continue_headers
  95. # is not None?
  96. return
  97. towrite = []
  98. # 100 Continue status line
  99. towrite.append(self.wfile_line)
  100. # Optional headers
  101. if self.hundred_continue_headers is not None:
  102. # 100 Continue headers
  103. for header in self.hundred_continue_headers:
  104. towrite.append(six.b('%s: %s\r\n' % header))
  105. # Blank line
  106. towrite.append(b'\r\n')
  107. self.wfile.writelines(towrite)
  108. self.wfile.flush()
  109. # Reinitialize chunk_length (expect more data)
  110. self.chunk_length = -1
  111. def _do_read(self, reader, length=None):
  112. if self.wfile is not None and not self.is_hundred_continue_response_sent:
  113. # 100 Continue response
  114. self.send_hundred_continue_response()
  115. self.is_hundred_continue_response_sent = True
  116. if (self.content_length is not None) and (
  117. length is None or length > self.content_length - self.position):
  118. length = self.content_length - self.position
  119. if not length:
  120. return b''
  121. try:
  122. read = reader(length)
  123. except greenio.SSL.ZeroReturnError:
  124. read = b''
  125. self.position += len(read)
  126. return read
  127. def _chunked_read(self, rfile, length=None, use_readline=False):
  128. if self.wfile is not None and not self.is_hundred_continue_response_sent:
  129. # 100 Continue response
  130. self.send_hundred_continue_response()
  131. self.is_hundred_continue_response_sent = True
  132. try:
  133. if length == 0:
  134. return b""
  135. if length and length < 0:
  136. length = None
  137. if use_readline:
  138. reader = self.rfile.readline
  139. else:
  140. reader = self.rfile.read
  141. response = []
  142. while self.chunk_length != 0:
  143. maxreadlen = self.chunk_length - self.position
  144. if length is not None and length < maxreadlen:
  145. maxreadlen = length
  146. if maxreadlen > 0:
  147. data = reader(maxreadlen)
  148. if not data:
  149. self.chunk_length = 0
  150. raise IOError("unexpected end of file while parsing chunked data")
  151. datalen = len(data)
  152. response.append(data)
  153. self.position += datalen
  154. if self.chunk_length == self.position:
  155. rfile.readline()
  156. if length is not None:
  157. length -= datalen
  158. if length == 0:
  159. break
  160. if use_readline and data[-1:] == b"\n":
  161. break
  162. else:
  163. try:
  164. self.chunk_length = int(rfile.readline().split(b";", 1)[0], 16)
  165. except ValueError as err:
  166. raise ChunkReadError(err)
  167. self.position = 0
  168. if self.chunk_length == 0:
  169. rfile.readline()
  170. except greenio.SSL.ZeroReturnError:
  171. pass
  172. return b''.join(response)
  173. def read(self, length=None):
  174. if self.chunked_input:
  175. return self._chunked_read(self.rfile, length)
  176. return self._do_read(self.rfile.read, length)
  177. def readline(self, size=None):
  178. if self.chunked_input:
  179. return self._chunked_read(self.rfile, size, True)
  180. else:
  181. return self._do_read(self.rfile.readline, size)
  182. def readlines(self, hint=None):
  183. if self.chunked_input:
  184. lines = []
  185. for line in iter(self.readline, b''):
  186. lines.append(line)
  187. if hint and hint > 0:
  188. hint -= len(line)
  189. if hint <= 0:
  190. break
  191. return lines
  192. else:
  193. return self._do_read(self.rfile.readlines, hint)
  194. def __iter__(self):
  195. return iter(self.read, b'')
  196. def get_socket(self):
  197. return self._sock
  198. def set_hundred_continue_response_headers(self, headers,
  199. capitalize_response_headers=True):
  200. # Response headers capitalization (default)
  201. # CONTent-TYpe: TExt/PlaiN -> Content-Type: TExt/PlaiN
  202. # Per HTTP RFC standard, header name is case-insensitive.
  203. # Please, fix your client to ignore header case if possible.
  204. if capitalize_response_headers:
  205. headers = [
  206. ('-'.join([x.capitalize() for x in key.split('-')]), value)
  207. for key, value in headers]
  208. self.hundred_continue_headers = headers
  209. def discard(self, buffer_size=16 << 10):
  210. while self.read(buffer_size):
  211. pass
  212. class HeaderLineTooLong(Exception):
  213. pass
  214. class HeadersTooLarge(Exception):
  215. pass
  216. def get_logger(log, debug):
  217. if callable(getattr(log, 'info', None)) \
  218. and callable(getattr(log, 'debug', None)):
  219. return log
  220. else:
  221. return LoggerFileWrapper(log or sys.stderr, debug)
  222. class LoggerNull(object):
  223. def __init__(self):
  224. pass
  225. def error(self, msg, *args, **kwargs):
  226. pass
  227. def info(self, msg, *args, **kwargs):
  228. pass
  229. def debug(self, msg, *args, **kwargs):
  230. pass
  231. def write(self, msg, *args):
  232. pass
  233. class LoggerFileWrapper(LoggerNull):
  234. def __init__(self, log, debug):
  235. self.log = log
  236. self._debug = debug
  237. def error(self, msg, *args, **kwargs):
  238. self.write(msg, *args)
  239. def info(self, msg, *args, **kwargs):
  240. self.write(msg, *args)
  241. def debug(self, msg, *args, **kwargs):
  242. if self._debug:
  243. self.write(msg, *args)
  244. def write(self, msg, *args):
  245. msg = msg + '\n'
  246. if args:
  247. msg = msg % args
  248. self.log.write(msg)
  249. class FileObjectForHeaders(object):
  250. def __init__(self, fp):
  251. self.fp = fp
  252. self.total_header_size = 0
  253. def readline(self, size=-1):
  254. sz = size
  255. if size < 0:
  256. sz = MAX_HEADER_LINE
  257. rv = self.fp.readline(sz)
  258. if len(rv) >= MAX_HEADER_LINE:
  259. raise HeaderLineTooLong()
  260. self.total_header_size += len(rv)
  261. if self.total_header_size > MAX_TOTAL_HEADER_SIZE:
  262. raise HeadersTooLarge()
  263. return rv
  264. class HttpProtocol(BaseHTTPServer.BaseHTTPRequestHandler):
  265. protocol_version = 'HTTP/1.1'
  266. minimum_chunk_size = MINIMUM_CHUNK_SIZE
  267. capitalize_response_headers = True
  268. # https://github.com/eventlet/eventlet/issues/295
  269. # Stdlib default is 0 (unbuffered), but then `wfile.writelines()` looses data
  270. # so before going back to unbuffered, remove any usage of `writelines`.
  271. wbufsize = 16 << 10
  272. def __init__(self, conn_state, server):
  273. self.request = conn_state[1]
  274. self.client_address = conn_state[0]
  275. self.conn_state = conn_state
  276. self.server = server
  277. self.setup()
  278. try:
  279. self.handle()
  280. finally:
  281. self.finish()
  282. def setup(self):
  283. # overriding SocketServer.setup to correctly handle SSL.Connection objects
  284. conn = self.connection = self.request
  285. # TCP_QUICKACK is a better alternative to disabling Nagle's algorithm
  286. # https://news.ycombinator.com/item?id=10607422
  287. if getattr(socket, 'TCP_QUICKACK', None):
  288. try:
  289. conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, True)
  290. except socket.error:
  291. pass
  292. try:
  293. self.rfile = conn.makefile('rb', self.rbufsize)
  294. self.wfile = conn.makefile('wb', self.wbufsize)
  295. except (AttributeError, NotImplementedError):
  296. if hasattr(conn, 'send') and hasattr(conn, 'recv'):
  297. # it's an SSL.Connection
  298. self.rfile = socket._fileobject(conn, "rb", self.rbufsize)
  299. self.wfile = socket._fileobject(conn, "wb", self.wbufsize)
  300. else:
  301. # it's a SSLObject, or a martian
  302. raise NotImplementedError(
  303. '''eventlet.wsgi doesn't support sockets of type {0}'''.format(type(conn)))
  304. def handle(self):
  305. self.close_connection = True
  306. while True:
  307. self.handle_one_request()
  308. if self.conn_state[2] == STATE_CLOSE:
  309. self.close_connection = 1
  310. if self.close_connection:
  311. break
  312. def _read_request_line(self):
  313. if self.rfile.closed:
  314. self.close_connection = 1
  315. return ''
  316. try:
  317. return self.rfile.readline(self.server.url_length_limit)
  318. except greenio.SSL.ZeroReturnError:
  319. pass
  320. except socket.error as e:
  321. last_errno = support.get_errno(e)
  322. if last_errno in BROKEN_SOCK:
  323. self.server.log.debug('({0}) connection reset by peer {1!r}'.format(
  324. self.server.pid,
  325. self.client_address))
  326. elif last_errno not in BAD_SOCK:
  327. raise
  328. return ''
  329. def handle_one_request(self):
  330. if self.server.max_http_version:
  331. self.protocol_version = self.server.max_http_version
  332. self.raw_requestline = self._read_request_line()
  333. if not self.raw_requestline:
  334. self.close_connection = 1
  335. return
  336. if len(self.raw_requestline) >= self.server.url_length_limit:
  337. self.wfile.write(RESPONSE_414)
  338. self.close_connection = 1
  339. return
  340. orig_rfile = self.rfile
  341. try:
  342. self.rfile = FileObjectForHeaders(self.rfile)
  343. if not self.parse_request():
  344. return
  345. except HeaderLineTooLong:
  346. self.wfile.write(
  347. b"HTTP/1.0 400 Header Line Too Long\r\n"
  348. b"Connection: close\r\nContent-length: 0\r\n\r\n")
  349. self.close_connection = 1
  350. return
  351. except HeadersTooLarge:
  352. self.wfile.write(
  353. b"HTTP/1.0 400 Headers Too Large\r\n"
  354. b"Connection: close\r\nContent-length: 0\r\n\r\n")
  355. self.close_connection = 1
  356. return
  357. finally:
  358. self.rfile = orig_rfile
  359. content_length = self.headers.get('content-length')
  360. if content_length is not None:
  361. try:
  362. if int(content_length) < 0:
  363. raise ValueError
  364. except ValueError:
  365. # Negative, or not an int at all
  366. self.wfile.write(
  367. b"HTTP/1.0 400 Bad Request\r\n"
  368. b"Connection: close\r\nContent-length: 0\r\n\r\n")
  369. self.close_connection = 1
  370. return
  371. self.environ = self.get_environ()
  372. self.application = self.server.app
  373. try:
  374. self.server.outstanding_requests += 1
  375. try:
  376. self.handle_one_response()
  377. except socket.error as e:
  378. # Broken pipe, connection reset by peer
  379. if support.get_errno(e) not in BROKEN_SOCK:
  380. raise
  381. finally:
  382. self.server.outstanding_requests -= 1
  383. def handle_one_response(self):
  384. start = time.time()
  385. headers_set = []
  386. headers_sent = []
  387. # Push the headers-sent state into the Input so it won't send a
  388. # 100 Continue response if we've already started a response.
  389. self.environ['wsgi.input'].headers_sent = headers_sent
  390. wfile = self.wfile
  391. result = None
  392. use_chunked = [False]
  393. length = [0]
  394. status_code = [200]
  395. def write(data):
  396. towrite = []
  397. if not headers_set:
  398. raise AssertionError("write() before start_response()")
  399. elif not headers_sent:
  400. status, response_headers = headers_set
  401. headers_sent.append(1)
  402. header_list = [header[0].lower() for header in response_headers]
  403. towrite.append(six.b('%s %s\r\n' % (self.protocol_version, status)))
  404. for header in response_headers:
  405. towrite.append(six.b('%s: %s\r\n' % header))
  406. # send Date header?
  407. if 'date' not in header_list:
  408. towrite.append(six.b('Date: %s\r\n' % (format_date_time(time.time()),)))
  409. client_conn = self.headers.get('Connection', '').lower()
  410. send_keep_alive = False
  411. if self.close_connection == 0 and \
  412. self.server.keepalive and (client_conn == 'keep-alive' or
  413. (self.request_version == 'HTTP/1.1' and
  414. not client_conn == 'close')):
  415. # only send keep-alives back to clients that sent them,
  416. # it's redundant for 1.1 connections
  417. send_keep_alive = (client_conn == 'keep-alive')
  418. self.close_connection = 0
  419. else:
  420. self.close_connection = 1
  421. if 'content-length' not in header_list:
  422. if self.request_version == 'HTTP/1.1':
  423. use_chunked[0] = True
  424. towrite.append(b'Transfer-Encoding: chunked\r\n')
  425. elif 'content-length' not in header_list:
  426. # client is 1.0 and therefore must read to EOF
  427. self.close_connection = 1
  428. if self.close_connection:
  429. towrite.append(b'Connection: close\r\n')
  430. elif send_keep_alive:
  431. towrite.append(b'Connection: keep-alive\r\n')
  432. towrite.append(b'\r\n')
  433. # end of header writing
  434. if use_chunked[0]:
  435. # Write the chunked encoding
  436. towrite.append(six.b("%x" % (len(data),)) + b"\r\n" + data + b"\r\n")
  437. else:
  438. towrite.append(data)
  439. wfile.writelines(towrite)
  440. wfile.flush()
  441. length[0] = length[0] + sum(map(len, towrite))
  442. def start_response(status, response_headers, exc_info=None):
  443. status_code[0] = status.split()[0]
  444. if exc_info:
  445. try:
  446. if headers_sent:
  447. # Re-raise original exception if headers sent
  448. six.reraise(exc_info[0], exc_info[1], exc_info[2])
  449. finally:
  450. # Avoid dangling circular ref
  451. exc_info = None
  452. # Response headers capitalization
  453. # CONTent-TYpe: TExt/PlaiN -> Content-Type: TExt/PlaiN
  454. # Per HTTP RFC standard, header name is case-insensitive.
  455. # Please, fix your client to ignore header case if possible.
  456. if self.capitalize_response_headers:
  457. if six.PY2:
  458. def cap(x):
  459. return x.capitalize()
  460. else:
  461. def cap(x):
  462. return x.encode('latin1').capitalize().decode('latin1')
  463. response_headers = [
  464. ('-'.join([cap(x) for x in key.split('-')]), value)
  465. for key, value in response_headers]
  466. headers_set[:] = [status, response_headers]
  467. return write
  468. try:
  469. try:
  470. result = self.application(self.environ, start_response)
  471. if (isinstance(result, _AlreadyHandled)
  472. or isinstance(getattr(result, '_obj', None), _AlreadyHandled)):
  473. self.close_connection = 1
  474. return
  475. # Set content-length if possible
  476. if not headers_sent and hasattr(result, '__len__') and \
  477. 'Content-Length' not in [h for h, _v in headers_set[1]]:
  478. headers_set[1].append(('Content-Length', str(sum(map(len, result)))))
  479. towrite = []
  480. towrite_size = 0
  481. just_written_size = 0
  482. minimum_write_chunk_size = int(self.environ.get(
  483. 'eventlet.minimum_write_chunk_size', self.minimum_chunk_size))
  484. for data in result:
  485. if len(data) == 0:
  486. continue
  487. if isinstance(data, six.text_type):
  488. data = data.encode('ascii')
  489. towrite.append(data)
  490. towrite_size += len(data)
  491. if towrite_size >= minimum_write_chunk_size:
  492. write(b''.join(towrite))
  493. towrite = []
  494. just_written_size = towrite_size
  495. towrite_size = 0
  496. if towrite:
  497. just_written_size = towrite_size
  498. write(b''.join(towrite))
  499. if not headers_sent or (use_chunked[0] and just_written_size):
  500. write(b'')
  501. except Exception:
  502. self.close_connection = 1
  503. tb = traceback.format_exc()
  504. self.server.log.info(tb)
  505. if not headers_sent:
  506. err_body = six.b(tb) if self.server.debug else b''
  507. start_response("500 Internal Server Error",
  508. [('Content-type', 'text/plain'),
  509. ('Content-length', len(err_body))])
  510. write(err_body)
  511. finally:
  512. if hasattr(result, 'close'):
  513. result.close()
  514. request_input = self.environ['eventlet.input']
  515. if (request_input.chunked_input or
  516. request_input.position < (request_input.content_length or 0)):
  517. # Read and discard body if there was no pending 100-continue
  518. if not request_input.wfile and self.close_connection == 0:
  519. try:
  520. request_input.discard()
  521. except ChunkReadError as e:
  522. self.close_connection = 1
  523. self.server.log.error((
  524. 'chunked encoding error while discarding request body.'
  525. + ' client={0} request="{1}" error="{2}"').format(
  526. self.get_client_address()[0], self.requestline, e,
  527. ))
  528. except IOError as e:
  529. self.close_connection = 1
  530. self.server.log.error((
  531. 'I/O error while discarding request body.'
  532. + ' client={0} request="{1}" error="{2}"').format(
  533. self.get_client_address()[0], self.requestline, e,
  534. ))
  535. finish = time.time()
  536. for hook, args, kwargs in self.environ['eventlet.posthooks']:
  537. hook(self.environ, *args, **kwargs)
  538. if self.server.log_output:
  539. client_host, client_port = self.get_client_address()
  540. self.server.log.info(self.server.log_format % {
  541. 'client_ip': client_host,
  542. 'client_port': client_port,
  543. 'date_time': self.log_date_time_string(),
  544. 'request_line': self.requestline,
  545. 'status_code': status_code[0],
  546. 'body_length': length[0],
  547. 'wall_seconds': finish - start,
  548. })
  549. def get_client_address(self):
  550. host, port = addr_to_host_port(self.client_address)
  551. if self.server.log_x_forwarded_for:
  552. forward = self.headers.get('X-Forwarded-For', '').replace(' ', '')
  553. if forward:
  554. host = forward + ',' + host
  555. return (host, port)
  556. def get_environ(self):
  557. env = self.server.get_environ()
  558. env['REQUEST_METHOD'] = self.command
  559. env['SCRIPT_NAME'] = ''
  560. pq = self.path.split('?', 1)
  561. env['RAW_PATH_INFO'] = pq[0]
  562. if six.PY2:
  563. env['PATH_INFO'] = urllib.parse.unquote(pq[0])
  564. else:
  565. env['PATH_INFO'] = urllib.parse.unquote(pq[0], encoding='latin1')
  566. if len(pq) > 1:
  567. env['QUERY_STRING'] = pq[1]
  568. ct = self.headers.get('content-type')
  569. if ct is None:
  570. try:
  571. ct = self.headers.type
  572. except AttributeError:
  573. ct = self.headers.get_content_type()
  574. env['CONTENT_TYPE'] = ct
  575. length = self.headers.get('content-length')
  576. if length:
  577. env['CONTENT_LENGTH'] = length
  578. env['SERVER_PROTOCOL'] = 'HTTP/1.0'
  579. sockname = self.request.getsockname()
  580. server_addr = addr_to_host_port(sockname)
  581. env['SERVER_NAME'] = server_addr[0]
  582. env['SERVER_PORT'] = str(server_addr[1])
  583. client_addr = addr_to_host_port(self.client_address)
  584. env['REMOTE_ADDR'] = client_addr[0]
  585. env['REMOTE_PORT'] = str(client_addr[1])
  586. env['GATEWAY_INTERFACE'] = 'CGI/1.1'
  587. try:
  588. headers = self.headers.headers
  589. except AttributeError:
  590. headers = self.headers._headers
  591. else:
  592. headers = [h.split(':', 1) for h in headers]
  593. env['headers_raw'] = headers_raw = tuple((k, v.strip(' \t\n\r')) for k, v in headers)
  594. for k, v in headers_raw:
  595. k = k.replace('-', '_').upper()
  596. if k in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
  597. # These do not get the HTTP_ prefix and were handled above
  598. continue
  599. envk = 'HTTP_' + k
  600. if envk in env:
  601. env[envk] += ',' + v
  602. else:
  603. env[envk] = v
  604. if env.get('HTTP_EXPECT', '').lower() == '100-continue':
  605. wfile = self.wfile
  606. wfile_line = b'HTTP/1.1 100 Continue\r\n'
  607. else:
  608. wfile = None
  609. wfile_line = None
  610. chunked = env.get('HTTP_TRANSFER_ENCODING', '').lower() == 'chunked'
  611. env['wsgi.input'] = env['eventlet.input'] = Input(
  612. self.rfile, length, self.connection, wfile=wfile, wfile_line=wfile_line,
  613. chunked_input=chunked)
  614. env['eventlet.posthooks'] = []
  615. return env
  616. def finish(self):
  617. try:
  618. BaseHTTPServer.BaseHTTPRequestHandler.finish(self)
  619. except socket.error as e:
  620. # Broken pipe, connection reset by peer
  621. if support.get_errno(e) not in BROKEN_SOCK:
  622. raise
  623. greenio.shutdown_safe(self.connection)
  624. self.connection.close()
  625. def handle_expect_100(self):
  626. return True
  627. class Server(BaseHTTPServer.HTTPServer):
  628. def __init__(self,
  629. socket,
  630. address,
  631. app,
  632. log=None,
  633. environ=None,
  634. max_http_version=None,
  635. protocol=HttpProtocol,
  636. minimum_chunk_size=None,
  637. log_x_forwarded_for=True,
  638. keepalive=True,
  639. log_output=True,
  640. log_format=DEFAULT_LOG_FORMAT,
  641. url_length_limit=MAX_REQUEST_LINE,
  642. debug=True,
  643. socket_timeout=None,
  644. capitalize_response_headers=True):
  645. self.outstanding_requests = 0
  646. self.socket = socket
  647. self.address = address
  648. self.log = LoggerNull()
  649. if log_output:
  650. self.log = get_logger(log, debug)
  651. self.app = app
  652. self.keepalive = keepalive
  653. self.environ = environ
  654. self.max_http_version = max_http_version
  655. self.protocol = protocol
  656. self.pid = os.getpid()
  657. self.minimum_chunk_size = minimum_chunk_size
  658. self.log_x_forwarded_for = log_x_forwarded_for
  659. self.log_output = log_output
  660. self.log_format = log_format
  661. self.url_length_limit = url_length_limit
  662. self.debug = debug
  663. self.socket_timeout = socket_timeout
  664. self.capitalize_response_headers = capitalize_response_headers
  665. if not self.capitalize_response_headers:
  666. warnings.warn("""capitalize_response_headers is disabled.
  667. Please, make sure you know what you are doing.
  668. HTTP headers names are case-insensitive per RFC standard.
  669. Most likely, you need to fix HTTP parsing in your client software.""",
  670. DeprecationWarning, stacklevel=3)
  671. def get_environ(self):
  672. d = {
  673. 'wsgi.errors': sys.stderr,
  674. 'wsgi.version': (1, 0),
  675. 'wsgi.multithread': True,
  676. 'wsgi.multiprocess': False,
  677. 'wsgi.run_once': False,
  678. 'wsgi.url_scheme': 'http',
  679. }
  680. # detect secure socket
  681. if hasattr(self.socket, 'do_handshake'):
  682. d['wsgi.url_scheme'] = 'https'
  683. d['HTTPS'] = 'on'
  684. if self.environ is not None:
  685. d.update(self.environ)
  686. return d
  687. def process_request(self, conn_state):
  688. # The actual request handling takes place in __init__, so we need to
  689. # set minimum_chunk_size before __init__ executes and we don't want to modify
  690. # class variable
  691. proto = new(self.protocol)
  692. if self.minimum_chunk_size is not None:
  693. proto.minimum_chunk_size = self.minimum_chunk_size
  694. proto.capitalize_response_headers = self.capitalize_response_headers
  695. try:
  696. proto.__init__(conn_state, self)
  697. except socket.timeout:
  698. # Expected exceptions are not exceptional
  699. conn_state[1].close()
  700. # similar to logging "accepted" in server()
  701. self.log.debug('({0}) timed out {1!r}'.format(self.pid, conn_state[0]))
  702. def log_message(self, message):
  703. raise AttributeError('''\
  704. eventlet.wsgi.server.log_message was deprecated and deleted.
  705. Please use server.log.info instead.''')
  706. try:
  707. new = types.InstanceType
  708. except AttributeError:
  709. new = lambda cls: cls.__new__(cls)
  710. try:
  711. import ssl
  712. ACCEPT_EXCEPTIONS = (socket.error, ssl.SSLError)
  713. ACCEPT_ERRNO = set((errno.EPIPE, errno.EBADF, errno.ECONNRESET,
  714. ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_SSL))
  715. except ImportError:
  716. ACCEPT_EXCEPTIONS = (socket.error,)
  717. ACCEPT_ERRNO = set((errno.EPIPE, errno.EBADF, errno.ECONNRESET))
  718. def socket_repr(sock):
  719. scheme = 'http'
  720. if hasattr(sock, 'do_handshake'):
  721. scheme = 'https'
  722. name = sock.getsockname()
  723. if sock.family == socket.AF_INET:
  724. hier_part = '//{0}:{1}'.format(*name)
  725. elif sock.family == socket.AF_INET6:
  726. hier_part = '//[{0}]:{1}'.format(*name[:2])
  727. elif sock.family == socket.AF_UNIX:
  728. hier_part = name
  729. else:
  730. hier_part = repr(name)
  731. return scheme + ':' + hier_part
  732. def server(sock, site,
  733. log=None,
  734. environ=None,
  735. max_size=None,
  736. max_http_version=DEFAULT_MAX_HTTP_VERSION,
  737. protocol=HttpProtocol,
  738. server_event=None,
  739. minimum_chunk_size=None,
  740. log_x_forwarded_for=True,
  741. custom_pool=None,
  742. keepalive=True,
  743. log_output=True,
  744. log_format=DEFAULT_LOG_FORMAT,
  745. url_length_limit=MAX_REQUEST_LINE,
  746. debug=True,
  747. socket_timeout=None,
  748. capitalize_response_headers=True):
  749. """Start up a WSGI server handling requests from the supplied server
  750. socket. This function loops forever. The *sock* object will be
  751. closed after server exits, but the underlying file descriptor will
  752. remain open, so if you have a dup() of *sock*, it will remain usable.
  753. .. warning::
  754. At the moment :func:`server` will always wait for active connections to finish before
  755. exiting, even if there's an exception raised inside it
  756. (*all* exceptions are handled the same way, including :class:`greenlet.GreenletExit`
  757. and those inheriting from `BaseException`).
  758. While this may not be an issue normally, when it comes to long running HTTP connections
  759. (like :mod:`eventlet.websocket`) it will become problematic and calling
  760. :meth:`~eventlet.greenthread.GreenThread.wait` on a thread that runs the server may hang,
  761. even after using :meth:`~eventlet.greenthread.GreenThread.kill`, as long
  762. as there are active connections.
  763. :param sock: Server socket, must be already bound to a port and listening.
  764. :param site: WSGI application function.
  765. :param log: logging.Logger instance or file-like object that logs should be written to.
  766. If a Logger instance is supplied, messages are sent to the INFO log level.
  767. If not specified, sys.stderr is used.
  768. :param environ: Additional parameters that go into the environ dictionary of every request.
  769. :param max_size: Maximum number of client connections opened at any time by this server.
  770. Default is 1024.
  771. :param max_http_version: Set to "HTTP/1.0" to make the server pretend it only supports HTTP 1.0.
  772. This can help with applications or clients that don't behave properly using HTTP 1.1.
  773. :param protocol: Protocol class. Deprecated.
  774. :param server_event: Used to collect the Server object. Deprecated.
  775. :param minimum_chunk_size: Minimum size in bytes for http chunks. This can be used to improve
  776. performance of applications which yield many small strings, though
  777. using it technically violates the WSGI spec. This can be overridden
  778. on a per request basis by setting environ['eventlet.minimum_write_chunk_size'].
  779. :param log_x_forwarded_for: If True (the default), logs the contents of the x-forwarded-for
  780. header in addition to the actual client ip address in the 'client_ip' field of the
  781. log line.
  782. :param custom_pool: A custom GreenPool instance which is used to spawn client green threads.
  783. If this is supplied, max_size is ignored.
  784. :param keepalive: If set to False, disables keepalives on the server; all connections will be
  785. closed after serving one request.
  786. :param log_output: A Boolean indicating if the server will log data or not.
  787. :param log_format: A python format string that is used as the template to generate log lines.
  788. The following values can be formatted into it: client_ip, date_time, request_line,
  789. status_code, body_length, wall_seconds. The default is a good example of how to
  790. use it.
  791. :param url_length_limit: A maximum allowed length of the request url. If exceeded, 414 error
  792. is returned.
  793. :param debug: True if the server should send exception tracebacks to the clients on 500 errors.
  794. If False, the server will respond with empty bodies.
  795. :param socket_timeout: Timeout for client connections' socket operations. Default None means
  796. wait forever.
  797. :param capitalize_response_headers: Normalize response headers' names to Foo-Bar.
  798. Default is True.
  799. """
  800. serv = Server(
  801. sock, sock.getsockname(),
  802. site, log,
  803. environ=environ,
  804. max_http_version=max_http_version,
  805. protocol=protocol,
  806. minimum_chunk_size=minimum_chunk_size,
  807. log_x_forwarded_for=log_x_forwarded_for,
  808. keepalive=keepalive,
  809. log_output=log_output,
  810. log_format=log_format,
  811. url_length_limit=url_length_limit,
  812. debug=debug,
  813. socket_timeout=socket_timeout,
  814. capitalize_response_headers=capitalize_response_headers,
  815. )
  816. if server_event is not None:
  817. warnings.warn(
  818. 'eventlet.wsgi.Server() server_event kwarg is deprecated and will be removed soon',
  819. DeprecationWarning, stacklevel=2)
  820. server_event.send(serv)
  821. if max_size is None:
  822. max_size = DEFAULT_MAX_SIMULTANEOUS_REQUESTS
  823. if custom_pool is not None:
  824. pool = custom_pool
  825. else:
  826. pool = eventlet.GreenPool(max_size)
  827. if not (hasattr(pool, 'spawn') and hasattr(pool, 'waitall')):
  828. raise AttributeError('''\
  829. eventlet.wsgi.Server pool must provide methods: `spawn`, `waitall`.
  830. If unsure, use eventlet.GreenPool.''')
  831. # [addr, socket, state]
  832. connections = {}
  833. def _clean_connection(_, conn):
  834. connections.pop(conn[0], None)
  835. conn[2] = STATE_CLOSE
  836. greenio.shutdown_safe(conn[1])
  837. conn[1].close()
  838. try:
  839. serv.log.info('({0}) wsgi starting up on {1}'.format(serv.pid, socket_repr(sock)))
  840. while is_accepting:
  841. try:
  842. client_socket, client_addr = sock.accept()
  843. client_socket.settimeout(serv.socket_timeout)
  844. serv.log.debug('({0}) accepted {1!r}'.format(serv.pid, client_addr))
  845. connections[client_addr] = connection = [client_addr, client_socket, STATE_IDLE]
  846. (pool.spawn(serv.process_request, connection)
  847. .link(_clean_connection, connection))
  848. except ACCEPT_EXCEPTIONS as e:
  849. if support.get_errno(e) not in ACCEPT_ERRNO:
  850. raise
  851. except (KeyboardInterrupt, SystemExit):
  852. serv.log.info('wsgi exiting')
  853. break
  854. finally:
  855. for cs in six.itervalues(connections):
  856. prev_state = cs[2]
  857. cs[2] = STATE_CLOSE
  858. if prev_state == STATE_IDLE:
  859. greenio.shutdown_safe(cs[1])
  860. pool.waitall()
  861. serv.log.info('({0}) wsgi exited, is_accepting={1}'.format(serv.pid, is_accepting))
  862. try:
  863. # NOTE: It's not clear whether we want this to leave the
  864. # socket open or close it. Use cases like Spawning want
  865. # the underlying fd to remain open, but if we're going
  866. # that far we might as well not bother closing sock at
  867. # all.
  868. sock.close()
  869. except socket.error as e:
  870. if support.get_errno(e) not in BROKEN_SOCK:
  871. traceback.print_exc()