1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
|
# Copyright (c) 2005, 2006 Allan Saddi <allan@saddi.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# $Id$
__author__ = 'Allan Saddi <allan@saddi.com>'
__version__ = '$Revision$'
import sys
import logging
import socket
import select
import errno
import cStringIO as StringIO
import signal
import datetime
import os
import warnings
import traceback
# Threads are required. If you want a non-threaded (forking) version, look at
# SWAP <http://www.idyll.org/~t/www-tools/wsgi/>.
import thread
import threading
__all__ = ['BaseSCGIServer']
from flup.server import NoDefault
# The main classes use this name for logging.
LoggerName = 'scgi-wsgi'
# Set up module-level logger.
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(logging.Formatter('%(asctime)s : %(message)s',
'%Y-%m-%d %H:%M:%S'))
logging.getLogger(LoggerName).addHandler(console)
del console
class ProtocolError(Exception):
"""
Exception raised when the server does something unexpected or
sends garbled data. Usually leads to a Connection closing.
"""
pass
def recvall(sock, length):
"""
Attempts to receive length bytes from a socket, blocking if necessary.
(Socket may be blocking or non-blocking.)
"""
dataList = []
recvLen = 0
while length:
try:
data = sock.recv(length)
except socket.error, e:
if e[0] == errno.EAGAIN:
select.select([sock], [], [])
continue
else:
raise
if not data: # EOF
break
dataList.append(data)
dataLen = len(data)
recvLen += dataLen
length -= dataLen
return ''.join(dataList), recvLen
def readNetstring(sock):
"""
Attempt to read a netstring from a socket.
"""
# First attempt to read the length.
size = ''
while True:
try:
c = sock.recv(1)
except socket.error, e:
if e[0] == errno.EAGAIN:
select.select([sock], [], [])
continue
else:
raise
if c == ':':
break
if not c:
raise EOFError
size += c
# Try to decode the length.
try:
size = int(size)
if size < 0:
raise ValueError
except ValueError:
raise ProtocolError, 'invalid netstring length'
# Now read the string.
s, length = recvall(sock, size)
if length < size:
raise EOFError
# Lastly, the trailer.
trailer, length = recvall(sock, 1)
if length < 1:
raise EOFError
if trailer != ',':
raise ProtocolError, 'invalid netstring trailer'
return s
class StdoutWrapper(object):
"""
Wrapper for sys.stdout so we know if data has actually been written.
"""
def __init__(self, stdout):
self._file = stdout
self.dataWritten = False
def write(self, data):
if data:
self.dataWritten = True
self._file.write(data)
def writelines(self, lines):
for line in lines:
self.write(line)
def __getattr__(self, name):
return getattr(self._file, name)
class Request(object):
"""
Encapsulates data related to a single request.
Public attributes:
environ - Environment variables from web server.
stdin - File-like object representing the request body.
stdout - File-like object for writing the response.
"""
def __init__(self, conn, environ, input, output):
self._conn = conn
self.environ = environ
self.stdin = input
self.stdout = StdoutWrapper(output)
self.logger = logging.getLogger(LoggerName)
def run(self):
self.logger.info('%s %s%s',
self.environ['REQUEST_METHOD'],
self.environ.get('SCRIPT_NAME', ''),
self.environ.get('PATH_INFO', ''))
start = datetime.datetime.now()
try:
self._conn.server.handler(self)
except:
self.logger.exception('Exception caught from handler')
if not self.stdout.dataWritten:
self._conn.server.error(self)
end = datetime.datetime.now()
handlerTime = end - start
self.logger.debug('%s %s%s done (%.3f secs)',
self.environ['REQUEST_METHOD'],
self.environ.get('SCRIPT_NAME', ''),
self.environ.get('PATH_INFO', ''),
handlerTime.seconds +
handlerTime.microseconds / 1000000.0)
class TimeoutException(Exception):
pass
class Connection(object):
"""
Represents a single client (web server) connection. A single request
is handled, after which the socket is closed.
"""
def __init__(self, sock, addr, server, timeout):
self._sock = sock
self._addr = addr
self.server = server
self._timeout = timeout
self.logger = logging.getLogger(LoggerName)
def timeout_handler(self, signum, frame):
self.logger.error('Timeout Exceeded')
self.logger.error("\n".join(traceback.format_stack(frame)))
raise TimeoutException
def run(self):
if len(self._addr) == 2:
self.logger.debug('Connection starting up (%s:%d)',
self._addr[0], self._addr[1])
try:
self.processInput()
except (EOFError, KeyboardInterrupt):
pass
except ProtocolError, e:
self.logger.error("Protocol error '%s'", str(e))
except:
self.logger.exception('Exception caught in Connection')
if len(self._addr) == 2:
self.logger.debug('Connection shutting down (%s:%d)',
self._addr[0], self._addr[1])
# All done!
self._sock.close()
def processInput(self):
# Read headers
headers = readNetstring(self._sock)
headers = headers.split('\x00')[:-1]
if len(headers) % 2 != 0:
raise ProtocolError, 'invalid headers'
environ = {}
for i in range(len(headers) / 2):
environ[headers[2*i]] = headers[2*i+1]
clen = environ.get('CONTENT_LENGTH')
if clen is None:
raise ProtocolError, 'missing CONTENT_LENGTH'
try:
clen = int(clen)
if clen < 0:
raise ValueError
except ValueError:
raise ProtocolError, 'invalid CONTENT_LENGTH'
self._sock.setblocking(1)
if clen:
input = self._sock.makefile('r')
else:
# Empty input.
input = StringIO.StringIO()
# stdout
output = self._sock.makefile('w')
# Allocate Request
req = Request(self, environ, input, output)
# If there is a timeout
if self._timeout:
old_alarm = signal.signal(signal.SIGALRM, self.timeout_handler)
signal.alarm(self._timeout)
# Run it.
req.run()
output.close()
input.close()
# Restore old handler if timeout was given
if self._timeout:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_alarm)
class BaseSCGIServer(object):
# What Request class to use.
requestClass = Request
def __init__(self, application, scriptName=NoDefault, environ=None,
multithreaded=True, multiprocess=False,
bindAddress=('localhost', 4000), umask=None,
allowedServers=NoDefault,
loggingLevel=logging.INFO, debug=False):
"""
scriptName is the initial portion of the URL path that "belongs"
to your application. It is used to determine PATH_INFO (which doesn't
seem to be passed in). An empty scriptName means your application
is mounted at the root of your virtual host.
environ, which must be a dictionary, can contain any additional
environment variables you want to pass to your application.
Set multithreaded to False if your application is not thread-safe.
Set multiprocess to True to explicitly set wsgi.multiprocess to
True. (Only makes sense with threaded servers.)
bindAddress is the address to bind to, which must be a string or
a tuple of length 2. If a tuple, the first element must be a string,
which is the host name or IPv4 address of a local interface. The
2nd element of the tuple is the port number. If a string, it will
be interpreted as a filename and a UNIX socket will be opened.
If binding to a UNIX socket, umask may be set to specify what
the umask is to be changed to before the socket is created in the
filesystem. After the socket is created, the previous umask is
restored.
allowedServers must be None or a list of strings representing the
IPv4 addresses of servers allowed to connect. None means accept
connections from anywhere. By default, it is a list containing
the single item '127.0.0.1'.
loggingLevel sets the logging level of the module-level logger.
"""
if environ is None:
environ = {}
self.application = application
self.scriptName = scriptName
self.environ = environ
self.multithreaded = multithreaded
self.multiprocess = multiprocess
self.debug = debug
self._bindAddress = bindAddress
self._umask = umask
if allowedServers is NoDefault:
allowedServers = ['127.0.0.1']
self._allowedServers = allowedServers
# Used to force single-threadedness.
self._appLock = thread.allocate_lock()
self.logger = logging.getLogger(LoggerName)
self.logger.setLevel(loggingLevel)
def _setupSocket(self):
"""Creates and binds the socket for communication with the server."""
oldUmask = None
if type(self._bindAddress) is str:
# Unix socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.unlink(self._bindAddress)
except OSError:
pass
if self._umask is not None:
oldUmask = os.umask(self._umask)
else:
# INET socket
assert type(self._bindAddress) is tuple
assert len(self._bindAddress) == 2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(self._bindAddress)
sock.listen(socket.SOMAXCONN)
if oldUmask is not None:
os.umask(oldUmask)
return sock
def _cleanupSocket(self, sock):
"""Closes the main socket."""
sock.close()
def _isClientAllowed(self, addr):
ret = self._allowedServers is None or \
len(addr) != 2 or \
(len(addr) == 2 and addr[0] in self._allowedServers)
if not ret:
self.logger.warning('Server connection from %s disallowed',
addr[0])
return ret
def handler(self, request):
"""
WSGI handler. Sets up WSGI environment, calls the application,
and sends the application's response.
"""
environ = request.environ
environ.update(self.environ)
environ['wsgi.version'] = (1,0)
environ['wsgi.input'] = request.stdin
environ['wsgi.errors'] = sys.stderr
environ['wsgi.multithread'] = self.multithreaded
environ['wsgi.multiprocess'] = self.multiprocess
environ['wsgi.run_once'] = False
if environ.get('HTTPS', 'off') in ('on', '1'):
environ['wsgi.url_scheme'] = 'https'
else:
environ['wsgi.url_scheme'] = 'http'
self._sanitizeEnv(environ)
headers_set = []
headers_sent = []
result = None
def write(data):
assert type(data) is str, 'write() argument must be string'
assert headers_set, 'write() before start_response()'
if not headers_sent:
status, responseHeaders = headers_sent[:] = headers_set
found = False
for header,value in responseHeaders:
if header.lower() == 'content-length':
found = True
break
if not found and result is not None:
try:
if len(result) == 1:
responseHeaders.append(('Content-Length',
str(len(data))))
except:
pass
s = 'Status: %s\r\n' % status
for header in responseHeaders:
s += '%s: %s\r\n' % header
s += '\r\n'
request.stdout.write(s)
request.stdout.write(data)
request.stdout.flush()
def start_response(status, response_headers, exc_info=None):
if exc_info:
try:
if headers_sent:
# Re-raise if too late
raise exc_info[0], exc_info[1], exc_info[2]
finally:
exc_info = None # avoid dangling circular ref
else:
assert not headers_set, 'Headers already set!'
assert type(status) is str, 'Status must be a string'
assert len(status) >= 4, 'Status must be at least 4 characters'
assert int(status[:3]), 'Status must begin with 3-digit code'
assert status[3] == ' ', 'Status must have a space after code'
assert type(response_headers) is list, 'Headers must be a list'
if __debug__:
for name,val in response_headers:
assert type(name) is str, 'Header name "%s" must be a string' % name
assert type(val) is str, 'Value of header "%s" must be a string' % name
headers_set[:] = [status, response_headers]
return write
if not self.multithreaded:
self._appLock.acquire()
try:
try:
result = self.application(environ, start_response)
try:
for data in result:
if data:
write(data)
if not headers_sent:
write('') # in case body was empty
finally:
if hasattr(result, 'close'):
result.close()
except socket.error, e:
if e[0] != errno.EPIPE:
raise # Don't let EPIPE propagate beyond server
finally:
if not self.multithreaded:
self._appLock.release()
def _sanitizeEnv(self, environ):
"""Fill-in/deduce missing values in environ."""
reqUri = None
if environ.has_key('REQUEST_URI'):
reqUri = environ['REQUEST_URI'].split('?', 1)
# Ensure QUERY_STRING exists
if not environ.has_key('QUERY_STRING') or not environ['QUERY_STRING']:
if reqUri is not None and len(reqUri) > 1:
environ['QUERY_STRING'] = reqUri[1]
else:
environ['QUERY_STRING'] = ''
# Check WSGI_SCRIPT_NAME
scriptName = environ.get('WSGI_SCRIPT_NAME')
if scriptName is None:
scriptName = self.scriptName
else:
warnings.warn('WSGI_SCRIPT_NAME environment variable for scgi '
'servers is deprecated',
DeprecationWarning)
if scriptName.lower() == 'none':
scriptName = None
if scriptName is None:
# Do nothing (most likely coming from cgi2scgi)
return
if scriptName is NoDefault:
# Pull SCRIPT_NAME/PATH_INFO from environment, with empty defaults
if not environ.has_key('SCRIPT_NAME'):
environ['SCRIPT_NAME'] = ''
if not environ.has_key('PATH_INFO') or not environ['PATH_INFO']:
if reqUri is not None:
scriptName = environ['SCRIPT_NAME']
if not reqUri[0].startswith(scriptName):
self.logger.warning('SCRIPT_NAME does not match request URI')
environ['PATH_INFO'] = reqUri[0][len(scriptName):]
else:
environ['PATH_INFO'] = ''
else:
# Configured scriptName
warnings.warn('Configured SCRIPT_NAME is deprecated\n'
'Do not use WSGI_SCRIPT_NAME or the scriptName\n'
'keyword parameter -- they will be going away',
DeprecationWarning)
value = environ['SCRIPT_NAME']
value += environ.get('PATH_INFO', '')
if not value.startswith(scriptName):
self.logger.warning('scriptName does not match request URI')
environ['PATH_INFO'] = value[len(scriptName):]
environ['SCRIPT_NAME'] = scriptName
def error(self, request):
"""
Override to provide custom error handling. Ideally, however,
all errors should be caught at the application level.
"""
if self.debug:
import cgitb
request.stdout.write('Status: 500 Internal Server Error\r\n' +
'Content-Type: text/html\r\n\r\n' +
cgitb.html(sys.exc_info()))
else:
errorpage = """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>Unhandled Exception</title>
</head><body>
<h1>Unhandled Exception</h1>
<p>An unhandled exception was thrown by the application.</p>
</body></html>
"""
request.stdout.write('Status: 500 Internal Server Error\r\n' +
'Content-Type: text/html\r\n\r\n' +
errorpage)
|