fcgi_base.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. # Copyright (c) 2002, 2003, 2005, 2006 Allan Saddi <allan@saddi.com>
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions
  6. # are met:
  7. # 1. Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  14. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  17. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  19. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  20. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23. # SUCH DAMAGE.
  24. #
  25. # $Id$
  26. __author__ = 'Allan Saddi <allan@saddi.com>'
  27. __version__ = '$Revision$'
  28. import sys
  29. import os
  30. import signal
  31. import struct
  32. import cStringIO as StringIO
  33. import select
  34. import socket
  35. import errno
  36. import traceback
  37. try:
  38. import thread
  39. import threading
  40. thread_available = True
  41. except ImportError:
  42. import dummy_thread as thread
  43. import dummy_threading as threading
  44. thread_available = False
  45. # Apparently 2.3 doesn't define SHUT_WR? Assume it is 1 in this case.
  46. if not hasattr(socket, 'SHUT_WR'):
  47. socket.SHUT_WR = 1
  48. __all__ = ['BaseFCGIServer']
  49. # Constants from the spec.
  50. FCGI_LISTENSOCK_FILENO = 0
  51. FCGI_HEADER_LEN = 8
  52. FCGI_VERSION_1 = 1
  53. FCGI_BEGIN_REQUEST = 1
  54. FCGI_ABORT_REQUEST = 2
  55. FCGI_END_REQUEST = 3
  56. FCGI_PARAMS = 4
  57. FCGI_STDIN = 5
  58. FCGI_STDOUT = 6
  59. FCGI_STDERR = 7
  60. FCGI_DATA = 8
  61. FCGI_GET_VALUES = 9
  62. FCGI_GET_VALUES_RESULT = 10
  63. FCGI_UNKNOWN_TYPE = 11
  64. FCGI_MAXTYPE = FCGI_UNKNOWN_TYPE
  65. FCGI_NULL_REQUEST_ID = 0
  66. FCGI_KEEP_CONN = 1
  67. FCGI_RESPONDER = 1
  68. FCGI_AUTHORIZER = 2
  69. FCGI_FILTER = 3
  70. FCGI_REQUEST_COMPLETE = 0
  71. FCGI_CANT_MPX_CONN = 1
  72. FCGI_OVERLOADED = 2
  73. FCGI_UNKNOWN_ROLE = 3
  74. FCGI_MAX_CONNS = 'FCGI_MAX_CONNS'
  75. FCGI_MAX_REQS = 'FCGI_MAX_REQS'
  76. FCGI_MPXS_CONNS = 'FCGI_MPXS_CONNS'
  77. FCGI_Header = '!BBHHBx'
  78. FCGI_BeginRequestBody = '!HB5x'
  79. FCGI_EndRequestBody = '!LB3x'
  80. FCGI_UnknownTypeBody = '!B7x'
  81. FCGI_EndRequestBody_LEN = struct.calcsize(FCGI_EndRequestBody)
  82. FCGI_UnknownTypeBody_LEN = struct.calcsize(FCGI_UnknownTypeBody)
  83. if __debug__:
  84. import time
  85. # Set non-zero to write debug output to a file.
  86. DEBUG = 0
  87. DEBUGLOG = '/tmp/fcgi.log'
  88. def _debug(level, msg):
  89. if DEBUG < level:
  90. return
  91. try:
  92. f = open(DEBUGLOG, 'a')
  93. f.write('%sfcgi: %s\n' % (time.ctime()[4:-4], msg))
  94. f.close()
  95. except:
  96. pass
  97. class InputStream(object):
  98. """
  99. File-like object representing FastCGI input streams (FCGI_STDIN and
  100. FCGI_DATA). Supports the minimum methods required by WSGI spec.
  101. """
  102. def __init__(self, conn):
  103. self._conn = conn
  104. # See Server.
  105. self._shrinkThreshold = conn.server.inputStreamShrinkThreshold
  106. self._buf = ''
  107. self._bufList = []
  108. self._pos = 0 # Current read position.
  109. self._avail = 0 # Number of bytes currently available.
  110. self._eof = False # True when server has sent EOF notification.
  111. def _shrinkBuffer(self):
  112. """Gets rid of already read data (since we can't rewind)."""
  113. if self._pos >= self._shrinkThreshold:
  114. self._buf = self._buf[self._pos:]
  115. self._avail -= self._pos
  116. self._pos = 0
  117. assert self._avail >= 0
  118. def _waitForData(self):
  119. """Waits for more data to become available."""
  120. self._conn.process_input()
  121. def read(self, n=-1):
  122. if self._pos == self._avail and self._eof:
  123. return ''
  124. while True:
  125. if n < 0 or (self._avail - self._pos) < n:
  126. # Not enough data available.
  127. if self._eof:
  128. # And there's no more coming.
  129. newPos = self._avail
  130. break
  131. else:
  132. # Wait for more data.
  133. self._waitForData()
  134. continue
  135. else:
  136. newPos = self._pos + n
  137. break
  138. # Merge buffer list, if necessary.
  139. if self._bufList:
  140. self._buf += ''.join(self._bufList)
  141. self._bufList = []
  142. r = self._buf[self._pos:newPos]
  143. self._pos = newPos
  144. self._shrinkBuffer()
  145. return r
  146. def readline(self, length=None):
  147. if self._pos == self._avail and self._eof:
  148. return ''
  149. while True:
  150. # Unfortunately, we need to merge the buffer list early.
  151. if self._bufList:
  152. self._buf += ''.join(self._bufList)
  153. self._bufList = []
  154. # Find newline.
  155. i = self._buf.find('\n', self._pos)
  156. if i < 0:
  157. # Not found?
  158. if self._eof:
  159. # No more data coming.
  160. newPos = self._avail
  161. break
  162. else:
  163. if length is not None and len(self._buf) >= length + self._pos:
  164. newPos = self._pos + length
  165. break
  166. # Wait for more to come.
  167. self._waitForData()
  168. continue
  169. else:
  170. newPos = i + 1
  171. break
  172. r = self._buf[self._pos:newPos]
  173. self._pos = newPos
  174. self._shrinkBuffer()
  175. return r
  176. def readlines(self, sizehint=0):
  177. total = 0
  178. lines = []
  179. line = self.readline()
  180. while line:
  181. lines.append(line)
  182. total += len(line)
  183. if 0 < sizehint <= total:
  184. break
  185. line = self.readline()
  186. return lines
  187. def __iter__(self):
  188. return self
  189. def next(self):
  190. r = self.readline()
  191. if not r:
  192. raise StopIteration
  193. return r
  194. def add_data(self, data):
  195. if not data:
  196. self._eof = True
  197. else:
  198. self._bufList.append(data)
  199. self._avail += len(data)
  200. class MultiplexedInputStream(InputStream):
  201. """
  202. A version of InputStream meant to be used with MultiplexedConnections.
  203. Assumes the MultiplexedConnection (the producer) and the Request
  204. (the consumer) are running in different threads.
  205. """
  206. def __init__(self, conn):
  207. super(MultiplexedInputStream, self).__init__(conn)
  208. # Arbitrates access to this InputStream (it's used simultaneously
  209. # by a Request and its owning Connection object).
  210. lock = threading.RLock()
  211. # Notifies Request thread that there is new data available.
  212. self._lock = threading.Condition(lock)
  213. def _waitForData(self):
  214. # Wait for notification from add_data().
  215. self._lock.wait()
  216. def read(self, n=-1):
  217. self._lock.acquire()
  218. try:
  219. return super(MultiplexedInputStream, self).read(n)
  220. finally:
  221. self._lock.release()
  222. def readline(self, length=None):
  223. self._lock.acquire()
  224. try:
  225. return super(MultiplexedInputStream, self).readline(length)
  226. finally:
  227. self._lock.release()
  228. def add_data(self, data):
  229. self._lock.acquire()
  230. try:
  231. super(MultiplexedInputStream, self).add_data(data)
  232. self._lock.notify()
  233. finally:
  234. self._lock.release()
  235. class OutputStream(object):
  236. """
  237. FastCGI output stream (FCGI_STDOUT/FCGI_STDERR). By default, calls to
  238. write() or writelines() immediately result in Records being sent back
  239. to the server. Buffering should be done in a higher level!
  240. """
  241. def __init__(self, conn, req, type, buffered=False):
  242. self._conn = conn
  243. self._req = req
  244. self._type = type
  245. self._buffered = buffered
  246. self._bufList = [] # Used if buffered is True
  247. self.dataWritten = False
  248. self.closed = False
  249. def _write(self, data):
  250. length = len(data)
  251. while length:
  252. toWrite = min(length, self._req.server.maxwrite - FCGI_HEADER_LEN)
  253. rec = Record(self._type, self._req.requestId)
  254. rec.contentLength = toWrite
  255. rec.contentData = data[:toWrite]
  256. self._conn.writeRecord(rec)
  257. data = data[toWrite:]
  258. length -= toWrite
  259. def write(self, data):
  260. assert not self.closed
  261. if not data:
  262. return
  263. self.dataWritten = True
  264. if self._buffered:
  265. self._bufList.append(data)
  266. else:
  267. self._write(data)
  268. def writelines(self, lines):
  269. assert not self.closed
  270. for line in lines:
  271. self.write(line)
  272. def flush(self):
  273. # Only need to flush if this OutputStream is actually buffered.
  274. if self._buffered:
  275. data = ''.join(self._bufList)
  276. self._bufList = []
  277. self._write(data)
  278. # Though available, the following should NOT be called by WSGI apps.
  279. def close(self):
  280. """Sends end-of-stream notification, if necessary."""
  281. if not self.closed and self.dataWritten:
  282. self.flush()
  283. rec = Record(self._type, self._req.requestId)
  284. self._conn.writeRecord(rec)
  285. self.closed = True
  286. class TeeOutputStream(object):
  287. """
  288. Simple wrapper around two or more output file-like objects that copies
  289. written data to all streams.
  290. """
  291. def __init__(self, streamList):
  292. self._streamList = streamList
  293. def write(self, data):
  294. for f in self._streamList:
  295. f.write(data)
  296. def writelines(self, lines):
  297. for line in lines:
  298. self.write(line)
  299. def flush(self):
  300. for f in self._streamList:
  301. f.flush()
  302. class StdoutWrapper(object):
  303. """
  304. Wrapper for sys.stdout so we know if data has actually been written.
  305. """
  306. def __init__(self, stdout):
  307. self._file = stdout
  308. self.dataWritten = False
  309. def write(self, data):
  310. if data:
  311. self.dataWritten = True
  312. self._file.write(data)
  313. def writelines(self, lines):
  314. for line in lines:
  315. self.write(line)
  316. def __getattr__(self, name):
  317. return getattr(self._file, name)
  318. def decode_pair(s, pos=0):
  319. """
  320. Decodes a name/value pair.
  321. The number of bytes decoded as well as the name/value pair
  322. are returned.
  323. """
  324. nameLength = ord(s[pos])
  325. if nameLength & 128:
  326. nameLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
  327. pos += 4
  328. else:
  329. pos += 1
  330. valueLength = ord(s[pos])
  331. if valueLength & 128:
  332. valueLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
  333. pos += 4
  334. else:
  335. pos += 1
  336. name = s[pos:pos+nameLength]
  337. pos += nameLength
  338. value = s[pos:pos+valueLength]
  339. pos += valueLength
  340. return (pos, (name, value))
  341. def encode_pair(name, value):
  342. """
  343. Encodes a name/value pair.
  344. The encoded string is returned.
  345. """
  346. nameLength = len(name)
  347. if nameLength < 128:
  348. s = chr(nameLength)
  349. else:
  350. s = struct.pack('!L', nameLength | 0x80000000L)
  351. valueLength = len(value)
  352. if valueLength < 128:
  353. s += chr(valueLength)
  354. else:
  355. s += struct.pack('!L', valueLength | 0x80000000L)
  356. return s + name + value
  357. class Record(object):
  358. """
  359. A FastCGI Record.
  360. Used for encoding/decoding records.
  361. """
  362. def __init__(self, type=FCGI_UNKNOWN_TYPE, requestId=FCGI_NULL_REQUEST_ID):
  363. self.version = FCGI_VERSION_1
  364. self.type = type
  365. self.requestId = requestId
  366. self.contentLength = 0
  367. self.paddingLength = 0
  368. self.contentData = ''
  369. def _recvall(sock, length):
  370. """
  371. Attempts to receive length bytes from a socket, blocking if necessary.
  372. (Socket may be blocking or non-blocking.)
  373. """
  374. dataList = []
  375. recvLen = 0
  376. while length:
  377. try:
  378. data = sock.recv(length)
  379. except socket.error, e:
  380. if e[0] == errno.EAGAIN:
  381. select.select([sock], [], [])
  382. continue
  383. else:
  384. raise
  385. if not data: # EOF
  386. break
  387. dataList.append(data)
  388. dataLen = len(data)
  389. recvLen += dataLen
  390. length -= dataLen
  391. return ''.join(dataList), recvLen
  392. _recvall = staticmethod(_recvall)
  393. def read(self, sock):
  394. """Read and decode a Record from a socket."""
  395. try:
  396. header, length = self._recvall(sock, FCGI_HEADER_LEN)
  397. except:
  398. raise EOFError
  399. if length < FCGI_HEADER_LEN:
  400. raise EOFError
  401. self.version, self.type, self.requestId, self.contentLength, \
  402. self.paddingLength = struct.unpack(FCGI_Header, header)
  403. if __debug__: _debug(9, 'read: fd = %d, type = %d, requestId = %d, '
  404. 'contentLength = %d' %
  405. (sock.fileno(), self.type, self.requestId,
  406. self.contentLength))
  407. if self.contentLength:
  408. try:
  409. self.contentData, length = self._recvall(sock,
  410. self.contentLength)
  411. except:
  412. raise EOFError
  413. if length < self.contentLength:
  414. raise EOFError
  415. if self.paddingLength:
  416. try:
  417. self._recvall(sock, self.paddingLength)
  418. except:
  419. raise EOFError
  420. def _sendall(sock, data):
  421. """
  422. Writes data to a socket and does not return until all the data is sent.
  423. """
  424. length = len(data)
  425. while length:
  426. try:
  427. sent = sock.send(data)
  428. except socket.error, e:
  429. if e[0] == errno.EAGAIN:
  430. select.select([], [sock], [])
  431. continue
  432. else:
  433. raise
  434. data = data[sent:]
  435. length -= sent
  436. _sendall = staticmethod(_sendall)
  437. def write(self, sock):
  438. """Encode and write a Record to a socket."""
  439. self.paddingLength = -self.contentLength & 7
  440. if __debug__: _debug(9, 'write: fd = %d, type = %d, requestId = %d, '
  441. 'contentLength = %d' %
  442. (sock.fileno(), self.type, self.requestId,
  443. self.contentLength))
  444. header = struct.pack(FCGI_Header, self.version, self.type,
  445. self.requestId, self.contentLength,
  446. self.paddingLength)
  447. self._sendall(sock, header)
  448. if self.contentLength:
  449. self._sendall(sock, self.contentData)
  450. if self.paddingLength:
  451. self._sendall(sock, '\x00'*self.paddingLength)
  452. class Request(object):
  453. """
  454. Represents a single FastCGI request.
  455. These objects are passed to your handler and is the main interface
  456. between your handler and the fcgi module. The methods should not
  457. be called by your handler. However, server, params, stdin, stdout,
  458. stderr, and data are free for your handler's use.
  459. """
  460. def __init__(self, conn, inputStreamClass):
  461. self._conn = conn
  462. self.server = conn.server
  463. self.params = {}
  464. self.stdin = inputStreamClass(conn)
  465. self.stdout = OutputStream(conn, self, FCGI_STDOUT)
  466. self.stderr = OutputStream(conn, self, FCGI_STDERR, buffered=True)
  467. self.data = inputStreamClass(conn)
  468. def run(self):
  469. """Runs the handler, flushes the streams, and ends the request."""
  470. try:
  471. protocolStatus, appStatus = self.server.handler(self)
  472. except:
  473. traceback.print_exc(file=self.stderr)
  474. self.stderr.flush()
  475. if not self.stdout.dataWritten:
  476. self.server.error(self)
  477. protocolStatus, appStatus = FCGI_REQUEST_COMPLETE, 0
  478. if __debug__: _debug(1, 'protocolStatus = %d, appStatus = %d' %
  479. (protocolStatus, appStatus))
  480. try:
  481. self._flush()
  482. self._end(appStatus, protocolStatus)
  483. except socket.error, e:
  484. if e[0] != errno.EPIPE:
  485. raise
  486. def _end(self, appStatus=0L, protocolStatus=FCGI_REQUEST_COMPLETE):
  487. self._conn.end_request(self, appStatus, protocolStatus)
  488. def _flush(self):
  489. self.stdout.close()
  490. self.stderr.close()
  491. class CGIRequest(Request):
  492. """A normal CGI request disguised as a FastCGI request."""
  493. def __init__(self, server):
  494. # These are normally filled in by Connection.
  495. self.requestId = 1
  496. self.role = FCGI_RESPONDER
  497. self.flags = 0
  498. self.aborted = False
  499. self.server = server
  500. self.params = dict(os.environ)
  501. self.stdin = sys.stdin
  502. self.stdout = StdoutWrapper(sys.stdout) # Oh, the humanity!
  503. self.stderr = sys.stderr
  504. self.data = StringIO.StringIO()
  505. def _end(self, appStatus=0L, protocolStatus=FCGI_REQUEST_COMPLETE):
  506. sys.exit(appStatus)
  507. def _flush(self):
  508. # Not buffered, do nothing.
  509. pass
  510. class Connection(object):
  511. """
  512. A Connection with the web server.
  513. Each Connection is associated with a single socket (which is
  514. connected to the web server) and is responsible for handling all
  515. the FastCGI message processing for that socket.
  516. """
  517. _multiplexed = False
  518. _inputStreamClass = InputStream
  519. def __init__(self, sock, addr, server):
  520. self._sock = sock
  521. self._addr = addr
  522. self.server = server
  523. # Active Requests for this Connection, mapped by request ID.
  524. self._requests = {}
  525. def _cleanupSocket(self):
  526. """Close the Connection's socket."""
  527. try:
  528. self._sock.shutdown(socket.SHUT_WR)
  529. except:
  530. return
  531. try:
  532. while True:
  533. r, w, e = select.select([self._sock], [], [])
  534. if not r or not self._sock.recv(1024):
  535. break
  536. except:
  537. pass
  538. self._sock.close()
  539. def run(self):
  540. """Begin processing data from the socket."""
  541. self._keepGoing = True
  542. while self._keepGoing:
  543. try:
  544. self.process_input()
  545. except (EOFError, KeyboardInterrupt):
  546. break
  547. except (select.error, socket.error), e:
  548. if e[0] == errno.EBADF: # Socket was closed by Request.
  549. break
  550. raise
  551. self._cleanupSocket()
  552. def process_input(self):
  553. """Attempt to read a single Record from the socket and process it."""
  554. # Currently, any children Request threads notify this Connection
  555. # that it is no longer needed by closing the Connection's socket.
  556. # We need to put a timeout on select, otherwise we might get
  557. # stuck in it indefinitely... (I don't like this solution.)
  558. while self._keepGoing:
  559. try:
  560. r, w, e = select.select([self._sock], [], [], 1.0)
  561. except ValueError:
  562. # Sigh. ValueError gets thrown sometimes when passing select
  563. # a closed socket.
  564. raise EOFError
  565. if r: break
  566. if not self._keepGoing:
  567. return
  568. rec = Record()
  569. rec.read(self._sock)
  570. if rec.type == FCGI_GET_VALUES:
  571. self._do_get_values(rec)
  572. elif rec.type == FCGI_BEGIN_REQUEST:
  573. self._do_begin_request(rec)
  574. elif rec.type == FCGI_ABORT_REQUEST:
  575. self._do_abort_request(rec)
  576. elif rec.type == FCGI_PARAMS:
  577. self._do_params(rec)
  578. elif rec.type == FCGI_STDIN:
  579. self._do_stdin(rec)
  580. elif rec.type == FCGI_DATA:
  581. self._do_data(rec)
  582. elif rec.requestId == FCGI_NULL_REQUEST_ID:
  583. self._do_unknown_type(rec)
  584. else:
  585. # Need to complain about this.
  586. pass
  587. def writeRecord(self, rec):
  588. """
  589. Write a Record to the socket.
  590. """
  591. rec.write(self._sock)
  592. def end_request(self, req, appStatus=0L,
  593. protocolStatus=FCGI_REQUEST_COMPLETE, remove=True):
  594. """
  595. End a Request.
  596. Called by Request objects. An FCGI_END_REQUEST Record is
  597. sent to the web server. If the web server no longer requires
  598. the connection, the socket is closed, thereby ending this
  599. Connection (run() returns).
  600. """
  601. rec = Record(FCGI_END_REQUEST, req.requestId)
  602. rec.contentData = struct.pack(FCGI_EndRequestBody, appStatus,
  603. protocolStatus)
  604. rec.contentLength = FCGI_EndRequestBody_LEN
  605. self.writeRecord(rec)
  606. if remove:
  607. del self._requests[req.requestId]
  608. if __debug__: _debug(2, 'end_request: flags = %d' % req.flags)
  609. if not (req.flags & FCGI_KEEP_CONN) and not self._requests:
  610. self._cleanupSocket()
  611. self._keepGoing = False
  612. def _do_get_values(self, inrec):
  613. """Handle an FCGI_GET_VALUES request from the web server."""
  614. outrec = Record(FCGI_GET_VALUES_RESULT)
  615. pos = 0
  616. while pos < inrec.contentLength:
  617. pos, (name, value) = decode_pair(inrec.contentData, pos)
  618. cap = self.server.capability.get(name)
  619. if cap is not None:
  620. outrec.contentData += encode_pair(name, str(cap))
  621. outrec.contentLength = len(outrec.contentData)
  622. self.writeRecord(outrec)
  623. def _do_begin_request(self, inrec):
  624. """Handle an FCGI_BEGIN_REQUEST from the web server."""
  625. role, flags = struct.unpack(FCGI_BeginRequestBody, inrec.contentData)
  626. req = self.server.request_class(self, self._inputStreamClass)
  627. req.requestId, req.role, req.flags = inrec.requestId, role, flags
  628. req.aborted = False
  629. if not self._multiplexed and self._requests:
  630. # Can't multiplex requests.
  631. self.end_request(req, 0L, FCGI_CANT_MPX_CONN, remove=False)
  632. else:
  633. self._requests[inrec.requestId] = req
  634. def _do_abort_request(self, inrec):
  635. """
  636. Handle an FCGI_ABORT_REQUEST from the web server.
  637. We just mark a flag in the associated Request.
  638. """
  639. req = self._requests.get(inrec.requestId)
  640. if req is not None:
  641. req.aborted = True
  642. def _start_request(self, req):
  643. """Run the request."""
  644. # Not multiplexed, so run it inline.
  645. req.run()
  646. def _do_params(self, inrec):
  647. """
  648. Handle an FCGI_PARAMS Record.
  649. If the last FCGI_PARAMS Record is received, start the request.
  650. """
  651. req = self._requests.get(inrec.requestId)
  652. if req is not None:
  653. if inrec.contentLength:
  654. pos = 0
  655. while pos < inrec.contentLength:
  656. pos, (name, value) = decode_pair(inrec.contentData, pos)
  657. req.params[name] = value
  658. else:
  659. self._start_request(req)
  660. def _do_stdin(self, inrec):
  661. """Handle the FCGI_STDIN stream."""
  662. req = self._requests.get(inrec.requestId)
  663. if req is not None:
  664. req.stdin.add_data(inrec.contentData)
  665. def _do_data(self, inrec):
  666. """Handle the FCGI_DATA stream."""
  667. req = self._requests.get(inrec.requestId)
  668. if req is not None:
  669. req.data.add_data(inrec.contentData)
  670. def _do_unknown_type(self, inrec):
  671. """Handle an unknown request type. Respond accordingly."""
  672. outrec = Record(FCGI_UNKNOWN_TYPE)
  673. outrec.contentData = struct.pack(FCGI_UnknownTypeBody, inrec.type)
  674. outrec.contentLength = FCGI_UnknownTypeBody_LEN
  675. self.writeRecord(rec)
  676. class MultiplexedConnection(Connection):
  677. """
  678. A version of Connection capable of handling multiple requests
  679. simultaneously.
  680. """
  681. _multiplexed = True
  682. _inputStreamClass = MultiplexedInputStream
  683. def __init__(self, sock, addr, server):
  684. super(MultiplexedConnection, self).__init__(sock, addr, server)
  685. # Used to arbitrate access to self._requests.
  686. lock = threading.RLock()
  687. # Notification is posted everytime a request completes, allowing us
  688. # to quit cleanly.
  689. self._lock = threading.Condition(lock)
  690. def _cleanupSocket(self):
  691. # Wait for any outstanding requests before closing the socket.
  692. self._lock.acquire()
  693. while self._requests:
  694. self._lock.wait()
  695. self._lock.release()
  696. super(MultiplexedConnection, self)._cleanupSocket()
  697. def writeRecord(self, rec):
  698. # Must use locking to prevent intermingling of Records from different
  699. # threads.
  700. self._lock.acquire()
  701. try:
  702. # Probably faster than calling super. ;)
  703. rec.write(self._sock)
  704. finally:
  705. self._lock.release()
  706. def end_request(self, req, appStatus=0L,
  707. protocolStatus=FCGI_REQUEST_COMPLETE, remove=True):
  708. self._lock.acquire()
  709. try:
  710. super(MultiplexedConnection, self).end_request(req, appStatus,
  711. protocolStatus,
  712. remove)
  713. self._lock.notify()
  714. finally:
  715. self._lock.release()
  716. def _do_begin_request(self, inrec):
  717. self._lock.acquire()
  718. try:
  719. super(MultiplexedConnection, self)._do_begin_request(inrec)
  720. finally:
  721. self._lock.release()
  722. def _do_abort_request(self, inrec):
  723. self._lock.acquire()
  724. try:
  725. super(MultiplexedConnection, self)._do_abort_request(inrec)
  726. finally:
  727. self._lock.release()
  728. def _start_request(self, req):
  729. thread.start_new_thread(req.run, ())
  730. def _do_params(self, inrec):
  731. self._lock.acquire()
  732. try:
  733. super(MultiplexedConnection, self)._do_params(inrec)
  734. finally:
  735. self._lock.release()
  736. def _do_stdin(self, inrec):
  737. self._lock.acquire()
  738. try:
  739. super(MultiplexedConnection, self)._do_stdin(inrec)
  740. finally:
  741. self._lock.release()
  742. def _do_data(self, inrec):
  743. self._lock.acquire()
  744. try:
  745. super(MultiplexedConnection, self)._do_data(inrec)
  746. finally:
  747. self._lock.release()
  748. class BaseFCGIServer(object):
  749. request_class = Request
  750. cgirequest_class = CGIRequest
  751. # The maximum number of bytes (per Record) to write to the server.
  752. # I've noticed mod_fastcgi has a relatively small receive buffer (8K or
  753. # so).
  754. maxwrite = 8192
  755. # Limits the size of the InputStream's string buffer to this size + the
  756. # server's maximum Record size. Since the InputStream is not seekable,
  757. # we throw away already-read data once this certain amount has been read.
  758. inputStreamShrinkThreshold = 102400 - 8192
  759. def __init__(self, application, environ=None,
  760. multithreaded=True, multiprocess=False,
  761. bindAddress=None, umask=None, multiplexed=False,
  762. debug=True, roles=(FCGI_RESPONDER,),
  763. forceCGI=False):
  764. """
  765. bindAddress, if present, must either be a string or a 2-tuple. If
  766. present, run() will open its own listening socket. You would use
  767. this if you wanted to run your application as an 'external' FastCGI
  768. app. (i.e. the webserver would no longer be responsible for starting
  769. your app) If a string, it will be interpreted as a filename and a UNIX
  770. socket will be opened. If a tuple, the first element, a string,
  771. is the interface name/IP to bind to, and the second element (an int)
  772. is the port number.
  773. If binding to a UNIX socket, umask may be set to specify what
  774. the umask is to be changed to before the socket is created in the
  775. filesystem. After the socket is created, the previous umask is
  776. restored.
  777. Set multiplexed to True if you want to handle multiple requests
  778. per connection. Some FastCGI backends (namely mod_fastcgi) don't
  779. multiplex requests at all, so by default this is off (which saves
  780. on thread creation/locking overhead). If threads aren't available,
  781. this keyword is ignored; it's not possible to multiplex requests
  782. at all.
  783. """
  784. if environ is None:
  785. environ = {}
  786. self.application = application
  787. self.environ = environ
  788. self.multithreaded = multithreaded
  789. self.multiprocess = multiprocess
  790. self.debug = debug
  791. self.roles = roles
  792. self.forceCGI = forceCGI
  793. self._bindAddress = bindAddress
  794. self._umask = umask
  795. # Used to force single-threadedness
  796. self._appLock = thread.allocate_lock()
  797. if thread_available:
  798. try:
  799. import resource
  800. # Attempt to glean the maximum number of connections
  801. # from the OS.
  802. maxConns = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
  803. except ImportError:
  804. maxConns = 100 # Just some made up number.
  805. maxReqs = maxConns
  806. if multiplexed:
  807. self._connectionClass = MultiplexedConnection
  808. maxReqs *= 5 # Another made up number.
  809. else:
  810. self._connectionClass = Connection
  811. self.capability = {
  812. FCGI_MAX_CONNS: maxConns,
  813. FCGI_MAX_REQS: maxReqs,
  814. FCGI_MPXS_CONNS: multiplexed and 1 or 0
  815. }
  816. else:
  817. self._connectionClass = Connection
  818. self.capability = {
  819. # If threads aren't available, these are pretty much correct.
  820. FCGI_MAX_CONNS: 1,
  821. FCGI_MAX_REQS: 1,
  822. FCGI_MPXS_CONNS: 0
  823. }
  824. def _setupSocket(self):
  825. if self._bindAddress is None: # Run as a normal FastCGI?
  826. isFCGI = True
  827. sock = socket.fromfd(FCGI_LISTENSOCK_FILENO, socket.AF_INET,
  828. socket.SOCK_STREAM)
  829. try:
  830. sock.getpeername()
  831. except socket.error, e:
  832. if e[0] == errno.ENOTSOCK:
  833. # Not a socket, assume CGI context.
  834. isFCGI = False
  835. elif e[0] != errno.ENOTCONN:
  836. raise
  837. # FastCGI/CGI discrimination is broken on Mac OS X.
  838. # Set the environment variable FCGI_FORCE_CGI to "Y" or "y"
  839. # if you want to run your app as a simple CGI. (You can do
  840. # this with Apache's mod_env [not loaded by default in OS X
  841. # client, ha ha] and the SetEnv directive.)
  842. if not isFCGI or self.forceCGI or \
  843. os.environ.get('FCGI_FORCE_CGI', 'N').upper().startswith('Y'):
  844. req = self.cgirequest_class(self)
  845. req.run()
  846. sys.exit(0)
  847. else:
  848. # Run as a server
  849. oldUmask = None
  850. if type(self._bindAddress) is str:
  851. # Unix socket
  852. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  853. try:
  854. os.unlink(self._bindAddress)
  855. except OSError:
  856. pass
  857. if self._umask is not None:
  858. oldUmask = os.umask(self._umask)
  859. else:
  860. # INET socket
  861. assert type(self._bindAddress) is tuple
  862. assert len(self._bindAddress) == 2
  863. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  864. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  865. sock.bind(self._bindAddress)
  866. sock.listen(socket.SOMAXCONN)
  867. if oldUmask is not None:
  868. os.umask(oldUmask)
  869. return sock
  870. def _cleanupSocket(self, sock):
  871. """Closes the main socket."""
  872. sock.close()
  873. def handler(self, req):
  874. """Special handler for WSGI."""
  875. if req.role not in self.roles:
  876. return FCGI_UNKNOWN_ROLE, 0
  877. # Mostly taken from example CGI gateway.
  878. environ = req.params
  879. environ.update(self.environ)
  880. environ['wsgi.version'] = (1,0)
  881. environ['wsgi.input'] = req.stdin
  882. if self._bindAddress is None:
  883. stderr = req.stderr
  884. else:
  885. stderr = TeeOutputStream((sys.stderr, req.stderr))
  886. environ['wsgi.errors'] = stderr
  887. environ['wsgi.multithread'] = not isinstance(req, CGIRequest) and \
  888. thread_available and self.multithreaded
  889. environ['wsgi.multiprocess'] = isinstance(req, CGIRequest) or \
  890. self.multiprocess
  891. environ['wsgi.run_once'] = isinstance(req, CGIRequest)
  892. if environ.get('HTTPS', 'off') in ('on', '1'):
  893. environ['wsgi.url_scheme'] = 'https'
  894. else:
  895. environ['wsgi.url_scheme'] = 'http'
  896. self._sanitizeEnv(environ)
  897. headers_set = []
  898. headers_sent = []
  899. result = None
  900. def write(data):
  901. assert type(data) is str, 'write() argument must be string'
  902. assert headers_set, 'write() before start_response()'
  903. if not headers_sent:
  904. status, responseHeaders = headers_sent[:] = headers_set
  905. found = False
  906. for header,value in responseHeaders:
  907. if header.lower() == 'content-length':
  908. found = True
  909. break
  910. if not found and result is not None:
  911. try:
  912. if len(result) == 1:
  913. responseHeaders.append(('Content-Length',
  914. str(len(data))))
  915. except:
  916. pass
  917. s = 'Status: %s\r\n' % status
  918. for header in responseHeaders:
  919. s += '%s: %s\r\n' % header
  920. s += '\r\n'
  921. req.stdout.write(s)
  922. req.stdout.write(data)
  923. req.stdout.flush()
  924. def start_response(status, response_headers, exc_info=None):
  925. if exc_info:
  926. try:
  927. if headers_sent:
  928. # Re-raise if too late
  929. raise exc_info[0], exc_info[1], exc_info[2]
  930. finally:
  931. exc_info = None # avoid dangling circular ref
  932. else:
  933. assert not headers_set, 'Headers already set!'
  934. assert type(status) is str, 'Status must be a string'
  935. assert len(status) >= 4, 'Status must be at least 4 characters'
  936. assert int(status[:3]), 'Status must begin with 3-digit code'
  937. assert status[3] == ' ', 'Status must have a space after code'
  938. assert type(response_headers) is list, 'Headers must be a list'
  939. if __debug__:
  940. for name,val in response_headers:
  941. assert type(name) is str, 'Header name "%s" must be a string' % name
  942. assert type(val) is str, 'Value of header "%s" must be a string' % name
  943. headers_set[:] = [status, response_headers]
  944. return write
  945. if not self.multithreaded:
  946. self._appLock.acquire()
  947. try:
  948. try:
  949. result = self.application(environ, start_response)
  950. try:
  951. for data in result:
  952. if data:
  953. write(data)
  954. if not headers_sent:
  955. write('') # in case body was empty
  956. finally:
  957. if hasattr(result, 'close'):
  958. result.close()
  959. except socket.error, e:
  960. if e[0] != errno.EPIPE:
  961. raise # Don't let EPIPE propagate beyond server
  962. finally:
  963. if not self.multithreaded:
  964. self._appLock.release()
  965. return FCGI_REQUEST_COMPLETE, 0
  966. def _sanitizeEnv(self, environ):
  967. """Ensure certain values are present, if required by WSGI."""
  968. if not environ.has_key('SCRIPT_NAME'):
  969. environ['SCRIPT_NAME'] = ''
  970. reqUri = None
  971. if environ.has_key('REQUEST_URI'):
  972. reqUri = environ['REQUEST_URI'].split('?', 1)
  973. if not environ.has_key('PATH_INFO') or not environ['PATH_INFO']:
  974. if reqUri is not None:
  975. environ['PATH_INFO'] = reqUri[0]
  976. else:
  977. environ['PATH_INFO'] = ''
  978. if not environ.has_key('QUERY_STRING') or not environ['QUERY_STRING']:
  979. if reqUri is not None and len(reqUri) > 1:
  980. environ['QUERY_STRING'] = reqUri[1]
  981. else:
  982. environ['QUERY_STRING'] = ''
  983. # If any of these are missing, it probably signifies a broken
  984. # server...
  985. for name,default in [('REQUEST_METHOD', 'GET'),
  986. ('SERVER_NAME', 'localhost'),
  987. ('SERVER_PORT', '80'),
  988. ('SERVER_PROTOCOL', 'HTTP/1.0')]:
  989. if not environ.has_key(name):
  990. environ['wsgi.errors'].write('%s: missing FastCGI param %s '
  991. 'required by WSGI!\n' %
  992. (self.__class__.__name__, name))
  993. environ[name] = default
  994. def error(self, req):
  995. """
  996. Called by Request if an exception occurs within the handler. May and
  997. should be overridden.
  998. """
  999. if self.debug:
  1000. import cgitb
  1001. req.stdout.write('Content-Type: text/html\r\n\r\n' +
  1002. cgitb.html(sys.exc_info()))
  1003. else:
  1004. errorpage = """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
  1005. <html><head>
  1006. <title>Unhandled Exception</title>
  1007. </head><body>
  1008. <h1>Unhandled Exception</h1>
  1009. <p>An unhandled exception was thrown by the application.</p>
  1010. </body></html>
  1011. """
  1012. req.stdout.write('Content-Type: text/html\r\n\r\n' +
  1013. errorpage)