1 """ high-speed, production ready, thread pooled, generic WSGI server.
2
3 Simplest example on how to use this module directly
4 (without using CherryPy's application machinery):
5
6 from cherrypy import wsgiserver
7
8 def my_crazy_app(environ, start_response):
9 status = '200 OK'
10 response_headers = [('Content-type','text/plain')]
11 start_response(status, response_headers)
12 return ['Hello world!\n']
13
14 server = wsgiserver.CherryPyWSGIServer(
15 ('0.0.0.0', 8070), my_crazy_app,
16 server_name='www.cherrypy.example')
17
18 The CherryPy WSGI server can serve as many WSGI applications
19 as you want in one instance by using a WSGIPathInfoDispatcher:
20
21 d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
22 server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)
23
24 Want SSL support? Just set these attributes:
25
26 server.ssl_certificate = <filename>
27 server.ssl_private_key = <filename>
28
29 if __name__ == '__main__':
30 try:
31 server.start()
32 except KeyboardInterrupt:
33 server.stop()
34
35 This won't call the CherryPy engine (application side) at all, only the
36 WSGI server, which is independant from the rest of CherryPy. Don't
37 let the name "CherryPyWSGIServer" throw you; the name merely reflects
38 its origin, not its coupling.
39 """
40
41
42 import base64
43 import Queue
44 import os
45 import re
46 quoted_slash = re.compile("(?i)%2F")
47 import rfc822
48 import socket
49 try:
50 import cStringIO as StringIO
51 except ImportError:
52 import StringIO
53 import sys
54 import threading
55 import time
56 import traceback
57 from urllib import unquote
58 from urlparse import urlparse
59 import warnings
60
61 try:
62 from OpenSSL import SSL
63 from OpenSSL import crypto
64 except ImportError:
65 SSL = None
66
67 import errno
68
70 """Return error numbers for all errors in errnames on this platform.
71
72 The 'errno' module contains different global constants depending on
73 the specific platform (OS). This function will return the list of
74 numeric values for a given list of potential names.
75 """
76 errno_names = dir(errno)
77 nums = [getattr(errno, k) for k in errnames if k in errno_names]
78
79 return dict.fromkeys(nums).keys()
80
81 socket_errors_to_ignore = plat_specific_errors(
82 "EPIPE", "ETIMEDOUT", "ECONNREFUSED", "ECONNRESET",
83 "EHOSTDOWN", "EHOSTUNREACH",
84 "WSAECONNABORTED", "WSAECONNREFUSED", "WSAECONNRESET",
85 "WSAENETRESET", "WSAETIMEDOUT")
86 socket_errors_to_ignore.append("timed out")
87
88 socket_errors_nonblocking = plat_specific_errors(
89 'EAGAIN', 'EWOULDBLOCK', 'WSAEWOULDBLOCK')
90
91 comma_separated_headers = ['ACCEPT', 'ACCEPT-CHARSET', 'ACCEPT-ENCODING',
92 'ACCEPT-LANGUAGE', 'ACCEPT-RANGES', 'ALLOW', 'CACHE-CONTROL',
93 'CONNECTION', 'CONTENT-ENCODING', 'CONTENT-LANGUAGE', 'EXPECT',
94 'IF-MATCH', 'IF-NONE-MATCH', 'PRAGMA', 'PROXY-AUTHENTICATE', 'TE',
95 'TRAILER', 'TRANSFER-ENCODING', 'UPGRADE', 'VARY', 'VIA', 'WARNING',
96 'WWW-AUTHENTICATE']
97
98
100 """A WSGI dispatcher for dispatch based on the PATH_INFO.
101
102 apps: a dict or list of (path_prefix, app) pairs.
103 """
104
106 try:
107 apps = apps.items()
108 except AttributeError:
109 pass
110
111
112 apps.sort()
113 apps.reverse()
114
115
116
117 self.apps = [(p.rstrip("/"), a) for p, a in apps]
118
119 - def __call__(self, environ, start_response):
120 path = environ["PATH_INFO"] or "/"
121 for p, app in self.apps:
122
123 if path.startswith(p + "/") or path == p:
124 environ = environ.copy()
125 environ["SCRIPT_NAME"] = environ["SCRIPT_NAME"] + p
126 environ["PATH_INFO"] = path[len(p):]
127 return app(environ, start_response)
128
129 start_response('404 Not Found', [('Content-Type', 'text/plain'),
130 ('Content-Length', '0')])
131 return ['']
132
133
136
138 """Wraps a file-like object, raising MaxSizeExceeded if too large."""
139
141 self.rfile = rfile
142 self.maxlen = maxlen
143 self.bytes_read = 0
144
146 if self.maxlen and self.bytes_read > self.maxlen:
147 raise MaxSizeExceeded()
148
149 - def read(self, size=None):
150 data = self.rfile.read(size)
151 self.bytes_read += len(data)
152 self._check_length()
153 return data
154
156 if size is not None:
157 data = self.rfile.readline(size)
158 self.bytes_read += len(data)
159 self._check_length()
160 return data
161
162
163
164 res = []
165 while True:
166 data = self.rfile.readline(256)
167 self.bytes_read += len(data)
168 self._check_length()
169 res.append(data)
170
171 if len(data) < 256 or data[-1:] == "\n":
172 return ''.join(res)
173
175
176 total = 0
177 lines = []
178 line = self.readline()
179 while line:
180 lines.append(line)
181 total += len(line)
182 if 0 < sizehint <= total:
183 break
184 line = self.readline()
185 return lines
186
189
192
194 data = self.rfile.next()
195 self.bytes_read += len(data)
196 self._check_length()
197 return data
198
199
201 """An HTTP Request (and response).
202
203 A single HTTP connection may consist of multiple request/response pairs.
204
205 sendall: the 'sendall' method from the connection's fileobject.
206 wsgi_app: the WSGI application to call.
207 environ: a partial WSGI environ (server and connection entries).
208 The caller MUST set the following entries:
209 * All wsgi.* entries, including .input
210 * SERVER_NAME and SERVER_PORT
211 * Any SSL_* entries
212 * Any custom entries like REMOTE_ADDR and REMOTE_PORT
213 * SERVER_SOFTWARE: the value to write in the "Server" response header.
214 * ACTUAL_SERVER_PROTOCOL: the value to write in the Status-Line of
215 the response. From RFC 2145: "An HTTP server SHOULD send a
216 response version equal to the highest version for which the
217 server is at least conditionally compliant, and whose major
218 version is less than or equal to the one received in the
219 request. An HTTP server MUST NOT send a version for which
220 it is not at least conditionally compliant."
221
222 outheaders: a list of header tuples to write in the response.
223 ready: when True, the request has been parsed and is ready to begin
224 generating the response. When False, signals the calling Connection
225 that the response should not be generated and the connection should
226 close.
227 close_connection: signals the calling Connection that the request
228 should close. This does not imply an error! The client and/or
229 server may each request that the connection be closed.
230 chunked_write: if True, output will be encoded with the "chunked"
231 transfer-coding. This value is set automatically inside
232 send_headers.
233 """
234
235 max_request_header_size = 0
236 max_request_body_size = 0
237
238 - def __init__(self, sendall, environ, wsgi_app):
239 self.rfile = environ['wsgi.input']
240 self.sendall = sendall
241 self.environ = environ.copy()
242 self.wsgi_app = wsgi_app
243
244 self.ready = False
245 self.started_response = False
246 self.status = ""
247 self.outheaders = []
248 self.sent_headers = False
249 self.close_connection = False
250 self.chunked_write = False
251
262
264
265
266
267
268
269
270
271 request_line = self.rfile.readline()
272 if not request_line:
273
274 self.ready = False
275 return
276
277 if request_line == "\r\n":
278
279
280
281
282 request_line = self.rfile.readline()
283 if not request_line:
284 self.ready = False
285 return
286
287 environ = self.environ
288
289 method, path, req_protocol = request_line.strip().split(" ", 2)
290 environ["REQUEST_METHOD"] = method
291
292
293 scheme, location, path, params, qs, frag = urlparse(path)
294
295 if frag:
296 self.simple_response("400 Bad Request",
297 "Illegal #fragment in Request-URI.")
298 return
299
300 if scheme:
301 environ["wsgi.url_scheme"] = scheme
302 if params:
303 path = path + ";" + params
304
305 environ["SCRIPT_NAME"] = ""
306
307
308
309
310
311
312
313 atoms = [unquote(x) for x in quoted_slash.split(path)]
314 path = "%2F".join(atoms)
315 environ["PATH_INFO"] = path
316
317
318
319 environ["QUERY_STRING"] = qs
320
321
322
323
324
325
326
327
328
329
330
331
332
333 rp = int(req_protocol[5]), int(req_protocol[7])
334 server_protocol = environ["ACTUAL_SERVER_PROTOCOL"]
335 sp = int(server_protocol[5]), int(server_protocol[7])
336 if sp[0] != rp[0]:
337 self.simple_response("505 HTTP Version Not Supported")
338 return
339
340 environ["SERVER_PROTOCOL"] = req_protocol
341 self.response_protocol = "HTTP/%s.%s" % min(rp, sp)
342
343
344 if location:
345 environ["SERVER_NAME"] = location
346
347
348 try:
349 self.read_headers()
350 except ValueError, ex:
351 self.simple_response("400 Bad Request", repr(ex.args))
352 return
353
354
355 creds = environ.get("HTTP_AUTHORIZATION", "").split(" ", 1)
356 environ["AUTH_TYPE"] = creds[0]
357 if creds[0].lower() == 'basic':
358 user, pw = base64.decodestring(creds[1]).split(":", 1)
359 environ["REMOTE_USER"] = user
360
361
362 if self.response_protocol == "HTTP/1.1":
363 if environ.get("HTTP_CONNECTION", "") == "close":
364 self.close_connection = True
365 else:
366
367 if environ.get("HTTP_CONNECTION", "") != "Keep-Alive":
368 self.close_connection = True
369
370
371 te = None
372 if self.response_protocol == "HTTP/1.1":
373 te = environ.get("HTTP_TRANSFER_ENCODING")
374 if te:
375 te = [x.strip().lower() for x in te.split(",") if x.strip()]
376
377 self.chunked_read = False
378
379 if te:
380 for enc in te:
381 if enc == "chunked":
382 self.chunked_read = True
383 else:
384
385
386 self.simple_response("501 Unimplemented")
387 self.close_connection = True
388 return
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407 if environ.get("HTTP_EXPECT", "") == "100-continue":
408 self.simple_response(100)
409
410 self.ready = True
411
413 """Read header lines from the incoming stream."""
414 environ = self.environ
415
416 while True:
417 line = self.rfile.readline()
418 if not line:
419
420 raise ValueError("Illegal end of headers.")
421
422 if line == '\r\n':
423
424 break
425
426 if line[0] in ' \t':
427
428 v = line.strip()
429 else:
430 k, v = line.split(":", 1)
431 k, v = k.strip().upper(), v.strip()
432 envname = "HTTP_" + k.replace("-", "_")
433
434 if k in comma_separated_headers:
435 existing = environ.get(envname)
436 if existing:
437 v = ", ".join((existing, v))
438 environ[envname] = v
439
440 ct = environ.pop("HTTP_CONTENT_TYPE", None)
441 if ct:
442 environ["CONTENT_TYPE"] = ct
443 cl = environ.pop("HTTP_CONTENT_LENGTH", None)
444 if cl:
445 environ["CONTENT_LENGTH"] = cl
446
448 """Decode the 'chunked' transfer coding."""
449 cl = 0
450 data = StringIO.StringIO()
451 while True:
452 line = self.rfile.readline().strip().split(";", 1)
453 chunk_size = int(line.pop(0), 16)
454 if chunk_size <= 0:
455 break
456
457 cl += chunk_size
458 data.write(self.rfile.read(chunk_size))
459 crlf = self.rfile.read(2)
460 if crlf != "\r\n":
461 self.simple_response("400 Bad Request",
462 "Bad chunked transfer coding "
463 "(expected '\\r\\n', got %r)" % crlf)
464 return
465
466
467 self.read_headers()
468
469 data.seek(0)
470 self.environ["wsgi.input"] = data
471 self.environ["CONTENT_LENGTH"] = str(cl) or ""
472 return True
473
475 """Call the appropriate WSGI app and write its iterable output."""
476
477
478
479 if self.chunked_read:
480
481 self.rfile.maxlen = self.max_request_body_size
482 else:
483 cl = int(self.environ.get("CONTENT_LENGTH", 0))
484 self.rfile.maxlen = min(cl, self.max_request_body_size)
485 self.rfile.bytes_read = 0
486
487 try:
488 self._respond()
489 except MaxSizeExceeded:
490 self.simple_response("413 Request Entity Too Large")
491 return
492
494 if self.chunked_read:
495 if not self.decode_chunked():
496 self.close_connection = True
497 return
498
499 response = self.wsgi_app(self.environ, self.start_response)
500 try:
501 for chunk in response:
502
503
504
505
506
507
508 if chunk:
509 self.write(chunk)
510 finally:
511 if hasattr(response, "close"):
512 response.close()
513
514 if (self.ready and not self.sent_headers):
515 self.sent_headers = True
516 self.send_headers()
517 if self.chunked_write:
518 self.sendall("0\r\n\r\n")
519
521 """Write a simple response back to the client."""
522 status = str(status)
523 buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status),
524 "Content-Length: %s\r\n" % len(msg),
525 "Content-Type: text/plain\r\n"]
526
527 if status[:3] == "413" and self.response_protocol == 'HTTP/1.1':
528
529 self.close_connection = True
530 buf.append("Connection: close\r\n")
531
532 buf.append("\r\n")
533 if msg:
534 buf.append(msg)
535 self.sendall("".join(buf))
536
538 """WSGI callable to begin the HTTP response."""
539 if self.started_response:
540 if not exc_info:
541 raise AssertionError("WSGI start_response called a second "
542 "time with no exc_info.")
543 else:
544 try:
545 raise exc_info[0], exc_info[1], exc_info[2]
546 finally:
547 exc_info = None
548 self.started_response = True
549 self.status = status
550 self.outheaders.extend(headers)
551 return self.write
552
554 """WSGI callable to write unbuffered data to the client.
555
556 This method is also used internally by start_response (to write
557 data from the iterable returned by the WSGI application).
558 """
559 if not self.started_response:
560 raise AssertionError("WSGI write called before start_response.")
561
562 if not self.sent_headers:
563 self.sent_headers = True
564 self.send_headers()
565
566 if self.chunked_write and chunk:
567 buf = [hex(len(chunk))[2:], "\r\n", chunk, "\r\n"]
568 chunk="".join(buf)
569 self.sendall(chunk)
570
572 """Assert, process, and send the HTTP response message-headers."""
573 hkeys = [key.lower() for key, value in self.outheaders]
574 status = int(self.status[:3])
575
576 if status == 413:
577
578 self.close_connection = True
579 elif "content-length" not in hkeys:
580
581
582
583 if status < 200 or status in (204, 205, 304):
584 pass
585 else:
586 if self.response_protocol == 'HTTP/1.1':
587
588 self.chunked_write = True
589 self.outheaders.append(("Transfer-Encoding", "chunked"))
590 else:
591
592 self.close_connection = True
593
594 if "connection" not in hkeys:
595 if self.response_protocol == 'HTTP/1.1':
596 if self.close_connection:
597 self.outheaders.append(("Connection", "close"))
598 else:
599 if not self.close_connection:
600 self.outheaders.append(("Connection", "Keep-Alive"))
601
602 if (not self.close_connection) and (not self.chunked_read):
603
604
605
606
607
608
609
610
611
612
613
614
615 size = self.rfile.maxlen - self.rfile.bytes_read
616 if size > 0:
617 self.rfile.read(size)
618
619 if "date" not in hkeys:
620 self.outheaders.append(("Date", rfc822.formatdate()))
621
622 if "server" not in hkeys:
623 self.outheaders.append(("Server", self.environ['SERVER_SOFTWARE']))
624
625 buf = [self.environ['ACTUAL_SERVER_PROTOCOL'], " ", self.status, "\r\n"]
626 try:
627 buf += [k + ": " + v + "\r\n" for k, v in self.outheaders]
628 except TypeError:
629 if not isinstance(k, str):
630 raise TypeError("WSGI response header key %r is not a string.")
631 if not isinstance(v, str):
632 raise TypeError("WSGI response header value %r is not a string.")
633 else:
634 raise
635 buf.append("\r\n")
636 self.sendall("".join(buf))
637
638
640 """Exception raised when a client speaks HTTP to an HTTPS socket."""
641 pass
642
643
645 """Wrap the given method with SSL error-trapping.
646
647 is_reader: if False (the default), EOF errors will be raised.
648 If True, EOF errors will return "" (to emulate normal sockets).
649 """
650 def ssl_method_wrapper(self, *args, **kwargs):
651
652 start = time.time()
653 while True:
654 try:
655 return method(self, *args, **kwargs)
656 except (SSL.WantReadError, SSL.WantWriteError):
657
658
659
660
661 time.sleep(self.ssl_retry)
662 except SSL.SysCallError, e:
663 if is_reader and e.args == (-1, 'Unexpected EOF'):
664 return ""
665
666 errnum = e.args[0]
667 if is_reader and errnum in socket_errors_to_ignore:
668 return ""
669 raise socket.error(errnum)
670 except SSL.Error, e:
671 if is_reader and e.args == (-1, 'Unexpected EOF'):
672 return ""
673
674 thirdarg = None
675 try:
676 thirdarg = e.args[0][0][2]
677 except IndexError:
678 pass
679
680 if is_reader and thirdarg == 'ssl handshake failure':
681 return ""
682 if thirdarg == 'http request':
683
684 raise NoSSLError()
685 raise
686 if time.time() - start > self.ssl_timeout:
687 raise socket.timeout("timed out")
688 return ssl_method_wrapper
689
703
704
706 """An HTTP connection (active socket).
707
708 socket: the raw socket object (usually TCP) for this connection.
709 wsgi_app: the WSGI application for this server/connection.
710 environ: a WSGI environ template. This will be copied for each request.
711
712 rfile: a fileobject for reading from the socket.
713 sendall: a function for writing (+ flush) to the socket.
714 """
715
716 rbufsize = -1
717 RequestHandlerClass = HTTPRequest
718 environ = {"wsgi.version": (1, 0),
719 "wsgi.url_scheme": "http",
720 "wsgi.multithread": True,
721 "wsgi.multiprocess": False,
722 "wsgi.run_once": False,
723 "wsgi.errors": sys.stderr,
724 }
725
726 - def __init__(self, sock, wsgi_app, environ):
748
750 """Read each request and respond appropriately."""
751 try:
752 while True:
753
754
755
756 req = None
757 req = self.RequestHandlerClass(self.sendall, self.environ,
758 self.wsgi_app)
759
760
761 req.parse_request()
762 if not req.ready:
763 return
764
765 req.respond()
766 if req.close_connection:
767 return
768
769 except socket.error, e:
770 errnum = e.args[0]
771 if errnum not in socket_errors_to_ignore:
772 if req:
773 req.simple_response("500 Internal Server Error",
774 format_exc())
775 return
776 except (KeyboardInterrupt, SystemExit):
777 raise
778 except NoSSLError:
779
780 req.sendall = self.socket._sock.sendall
781 req.simple_response("400 Bad Request",
782 "The client sent a plain HTTP request, but "
783 "this server only speaks HTTPS on this port.")
784 except:
785 if req:
786 req.simple_response("500 Internal Server Error", format_exc())
787
789 """Close the socket underlying this connection."""
790 self.rfile.close()
791 self.socket.close()
792
793
801
802
803 _SHUTDOWNREQUEST = None
804
806 """Thread which continuously polls a Queue for Connection objects.
807
808 server: the HTTP Server which spawned this thread, and which owns the
809 Queue and is placing active connections into it.
810 ready: a simple flag for the calling server to know when this thread
811 has begun polling the Queue.
812
813 Due to the timing issues of polling a Queue, a WorkerThread does not
814 check its own 'ready' flag after it has started. To stop the thread,
815 it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue
816 (one for each running WorkerThread).
817 """
818
819 conn = None
820
822 self.ready = False
823 self.server = server
824 threading.Thread.__init__(self)
825
842
843
845 """A Request Queue for the CherryPyWSGIServer which pools threads."""
846
847 - def __init__(self, server, min=10, max=-1):
848 self.server = server
849 self.min = min
850 self.max = max
851 self._threads = []
852 self._queue = Queue.Queue()
853 self.get = self._queue.get
854
856 """Start the pool of threads."""
857 for i in xrange(self.min):
858 self._threads.append(WorkerThread(self.server))
859 for worker in self._threads:
860 worker.setName("CP WSGIServer " + worker.getName())
861 worker.start()
862 for worker in self._threads:
863 while not worker.ready:
864 time.sleep(.1)
865
867 """Number of worker threads which are idle. Read-only."""
868 return len([t for t in self._threads if t.conn is None])
869 idle = property(_get_idle, doc=_get_idle.__doc__)
870
871 - def put(self, obj):
872 self._queue.put(obj)
873 if obj is _SHUTDOWNREQUEST:
874 return
875
876
877
878 for t in self._threads:
879 if not t.isAlive():
880 self._threads.remove(t)
881
882 - def grow(self, amount):
883 """Spawn new worker threads (not above self.max)."""
884 for i in xrange(amount):
885 if self.max > 0 and len(self._threads) >= self.max:
886 break
887 worker = WorkerThread(self.server)
888 worker.setName("CP WSGIServer " + worker.getName())
889 self._threads.append(worker)
890 worker.start()
891
893 """Kill off worker threads (not below self.min)."""
894 for i in xrange(min(amount, len(self._threads) - self.min)):
895
896
897
898
899 self._queue.put(_SHUTDOWNREQUEST)
900
901 - def stop(self, timeout=5):
902
903
904 for worker in self._threads:
905 self._queue.put(_SHUTDOWNREQUEST)
906
907
908 current = threading.currentThread()
909 while self._threads:
910 worker = self._threads.pop()
911 if worker is not current and worker.isAlive():
912 try:
913 if timeout is None or timeout < 0:
914 worker.join()
915 else:
916 worker.join(timeout)
917 if worker.isAlive():
918
919
920 c = worker.conn
921 if c and not c.rfile.closed:
922 if SSL and isinstance(c.socket, SSL.ConnectionType):
923
924 c.socket.shutdown()
925 else:
926 c.socket.shutdown(socket.SHUT_RD)
927 worker.join()
928 except (AssertionError,
929
930
931 KeyboardInterrupt), exc1:
932 pass
933
934
935
937 """A thread-safe wrapper for an SSL.Connection.
938
939 *args: the arguments to create the wrapped SSL.Connection(*args).
940 """
941
943 self._ssl_conn = SSL.Connection(*args)
944 self._lock = threading.RLock()
945
946 for f in ('get_context', 'pending', 'send', 'write', 'recv', 'read',
947 'renegotiate', 'bind', 'listen', 'connect', 'accept',
948 'setblocking', 'fileno', 'shutdown', 'close', 'get_cipher_list',
949 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
950 'makefile', 'get_app_data', 'set_app_data', 'state_string',
951 'sock_shutdown', 'get_peer_certificate', 'want_read',
952 'want_write', 'set_connect_state', 'set_accept_state',
953 'connect_ex', 'sendall', 'settimeout'):
954 exec """def %s(self, *args):
955 self._lock.acquire()
956 try:
957 return self._ssl_conn.%s(*args)
958 finally:
959 self._lock.release()
960 """ % (f, f)
961
962
963
965 """An HTTP server for WSGI.
966
967 bind_addr: The interface on which to listen for connections.
968 For TCP sockets, a (host, port) tuple. Host values may be any IPv4
969 or IPv6 address, or any valid hostname. The string 'localhost' is a
970 synonym for '127.0.0.1' (or '::1', if your hosts file prefers IPv6).
971 The string '0.0.0.0' is a special IPv4 entry meaning "any active
972 interface" (INADDR_ANY), and '::' is the similar IN6ADDR_ANY for
973 IPv6. The empty string or None are not allowed.
974
975 For UNIX sockets, supply the filename as a string.
976 wsgi_app: the WSGI 'application callable'; multiple WSGI applications
977 may be passed as (path_prefix, app) pairs.
978 numthreads: the number of worker threads to create (default 10).
979 server_name: the string to set for WSGI's SERVER_NAME environ entry.
980 Defaults to socket.gethostname().
981 max: the maximum number of queued requests (defaults to -1 = no limit).
982 request_queue_size: the 'backlog' argument to socket.listen();
983 specifies the maximum number of queued connections (default 5).
984 timeout: the timeout in seconds for accepted connections (default 10).
985
986 protocol: the version string to write in the Status-Line of all
987 HTTP responses. For example, "HTTP/1.1" (the default). This
988 also limits the supported features used in the response.
989
990
991 SSL/HTTPS
992 ---------
993 The OpenSSL module must be importable for SSL functionality.
994 You can obtain it from http://pyopenssl.sourceforge.net/
995
996 ssl_certificate: the filename of the server SSL certificate.
997 ssl_privatekey: the filename of the server's private key file.
998
999 If either of these is None (both are None by default), this server
1000 will not use SSL. If both are given and are valid, they will be read
1001 on server start and used in the SSL context for the listening socket.
1002 """
1003
1004 protocol = "HTTP/1.1"
1005 _bind_addr = "127.0.0.1"
1006 version = "CherryPy/3.1.0beta3"
1007 ready = False
1008 _interrupt = None
1009 ConnectionClass = HTTPConnection
1010 environ = {}
1011
1012
1013 ssl_certificate = None
1014 ssl_private_key = None
1015
1016 - def __init__(self, bind_addr, wsgi_app, numthreads=10, server_name=None,
1017 max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5):
1018 self.requests = ThreadPool(self, min=numthreads or 1, max=max)
1019
1020 if callable(wsgi_app):
1021
1022
1023 self.wsgi_app = wsgi_app
1024 else:
1025
1026
1027
1028 warnings.warn("The ability to pass multiple apps is deprecated "
1029 "and will be removed in 3.2. You should explicitly "
1030 "include a WSGIPathInfoDispatcher instead.",
1031 DeprecationWarning)
1032 self.wsgi_app = WSGIPathInfoDispatcher(wsgi_app)
1033
1034 self.bind_addr = bind_addr
1035 if not server_name:
1036 server_name = socket.gethostname()
1037 self.server_name = server_name
1038 self.request_queue_size = request_queue_size
1039
1040 self.timeout = timeout
1041 self.shutdown_timeout = shutdown_timeout
1042
1044 return self.requests.min
1046 self.requests.min = value
1047 numthreads = property(_get_numthreads, _set_numthreads)
1048
1050 return "%s.%s(%r)" % (self.__module__, self.__class__.__name__,
1051 self.bind_addr)
1052
1056 if isinstance(value, tuple) and value[0] in ('', None):
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067 raise ValueError("Host values of '' or None are not allowed. "
1068 "Use '0.0.0.0' (IPv4) or '::' (IPv6) instead "
1069 "to listen on all active interfaces.")
1070 self._bind_addr = value
1071 bind_addr = property(_get_bind_addr, _set_bind_addr,
1072 doc="""The interface on which to listen for connections.
1073
1074 For TCP sockets, a (host, port) tuple. Host values may be any IPv4
1075 or IPv6 address, or any valid hostname. The string 'localhost' is a
1076 synonym for '127.0.0.1' (or '::1', if your hosts file prefers IPv6).
1077 The string '0.0.0.0' is a special IPv4 entry meaning "any active
1078 interface" (INADDR_ANY), and '::' is the similar IN6ADDR_ANY for
1079 IPv6. The empty string or None are not allowed.
1080
1081 For UNIX sockets, supply the filename as a string.""")
1082
1084 """Run the server forever."""
1085
1086
1087
1088
1089 self._interrupt = None
1090
1091
1092 if isinstance(self.bind_addr, basestring):
1093
1094
1095
1096 try: os.unlink(self.bind_addr)
1097 except: pass
1098
1099
1100 try: os.chmod(self.bind_addr, 0777)
1101 except: pass
1102
1103 info = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)]
1104 else:
1105
1106
1107 host, port = self.bind_addr
1108 try:
1109 info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
1110 socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
1111 except socket.gaierror:
1112
1113 info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", self.bind_addr)]
1114
1115 self.socket = None
1116 msg = "No socket could be created"
1117 for res in info:
1118 af, socktype, proto, canonname, sa = res
1119 try:
1120 self.bind(af, socktype, proto)
1121 except socket.error, msg:
1122 if self.socket:
1123 self.socket.close()
1124 self.socket = None
1125 continue
1126 break
1127 if not self.socket:
1128 raise socket.error, msg
1129
1130
1131 self.socket.settimeout(1)
1132 self.socket.listen(self.request_queue_size)
1133
1134
1135 self.requests.start()
1136
1137 self.ready = True
1138 while self.ready:
1139 self.tick()
1140 if self.interrupt:
1141 while self.interrupt is True:
1142
1143 time.sleep(0.1)
1144 if self.interrupt:
1145 raise self.interrupt
1146
1147 - def bind(self, family, type, proto=0):
1148 """Create (or recreate) the actual socket object."""
1149 self.socket = socket.socket(family, type, proto)
1150 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1151
1152 if self.ssl_certificate and self.ssl_private_key:
1153 if SSL is None:
1154 raise ImportError("You must install pyOpenSSL to use HTTPS.")
1155
1156
1157 ctx = SSL.Context(SSL.SSLv23_METHOD)
1158 ctx.use_privatekey_file(self.ssl_private_key)
1159 ctx.use_certificate_file(self.ssl_certificate)
1160 self.socket = SSLConnection(ctx, self.socket)
1161 self.populate_ssl_environ()
1162 self.socket.bind(self.bind_addr)
1163
1165 """Accept a new connection and put it on the Queue."""
1166 try:
1167 s, addr = self.socket.accept()
1168 if not self.ready:
1169 return
1170 if hasattr(s, 'settimeout'):
1171 s.settimeout(self.timeout)
1172
1173 environ = self.environ.copy()
1174
1175
1176 environ["SERVER_SOFTWARE"] = "%s WSGI Server" % self.version
1177
1178
1179
1180 environ["ACTUAL_SERVER_PROTOCOL"] = self.protocol
1181 environ["SERVER_NAME"] = self.server_name
1182
1183 if isinstance(self.bind_addr, basestring):
1184
1185
1186 environ["SERVER_PORT"] = ""
1187 else:
1188 environ["SERVER_PORT"] = str(self.bind_addr[1])
1189
1190
1191 environ["REMOTE_ADDR"] = addr[0]
1192 environ["REMOTE_PORT"] = str(addr[1])
1193
1194 conn = self.ConnectionClass(s, self.wsgi_app, environ)
1195 self.requests.put(conn)
1196 except socket.timeout:
1197
1198
1199
1200 return
1201 except socket.error, x:
1202 if hasattr(errno, "EINTR") and x.args[0] == errno.EINTR:
1203
1204
1205
1206
1207
1208 return
1209 msg = x.args[1]
1210 if msg in ("Bad file descriptor", "Socket operation on non-socket"):
1211
1212 return
1213 if msg == "Resource temporarily unavailable":
1214
1215 return
1216 raise
1217
1224 interrupt = property(_get_interrupt, _set_interrupt,
1225 doc="Set this to an Exception instance to "
1226 "interrupt the server.")
1227
1229 """Gracefully shutdown a server that is serving forever."""
1230 self.ready = False
1231
1232 sock = getattr(self, "socket", None)
1233 if sock:
1234 if not isinstance(self.bind_addr, basestring):
1235
1236 try:
1237 host, port = sock.getsockname()[:2]
1238 except socket.error, x:
1239 if x.args[1] != "Bad file descriptor":
1240 raise
1241 else:
1242
1243
1244
1245
1246 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
1247 socket.SOCK_STREAM):
1248 af, socktype, proto, canonname, sa = res
1249 s = None
1250 try:
1251 s = socket.socket(af, socktype, proto)
1252
1253
1254 s.settimeout(1.0)
1255 s.connect((host, port))
1256 s.close()
1257 except socket.error:
1258 if s:
1259 s.close()
1260 if hasattr(sock, "close"):
1261 sock.close()
1262 self.socket = None
1263
1264 self.requests.stop(self.shutdown_timeout)
1265
1267 """Create WSGI environ entries to be merged into each request."""
1268 cert = open(self.ssl_certificate).read()
1269 cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
1270 ssl_environ = {
1271 "wsgi.url_scheme": "https",
1272 "HTTPS": "on",
1273
1274
1275
1276
1277
1278 }
1279
1280
1281 ssl_environ.update({
1282 'SSL_SERVER_M_VERSION': cert.get_version(),
1283 'SSL_SERVER_M_SERIAL': cert.get_serial_number(),
1284
1285
1286 })
1287
1288 for prefix, dn in [("I", cert.get_issuer()),
1289 ("S", cert.get_subject())]:
1290
1291
1292
1293 dnstr = str(dn)[18:-2]
1294
1295 wsgikey = 'SSL_SERVER_%s_DN' % prefix
1296 ssl_environ[wsgikey] = dnstr
1297
1298
1299
1300 while dnstr:
1301 pos = dnstr.rfind("=")
1302 dnstr, value = dnstr[:pos], dnstr[pos + 1:]
1303 pos = dnstr.rfind("/")
1304 dnstr, key = dnstr[:pos], dnstr[pos + 1:]
1305 if key and value:
1306 wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key)
1307 ssl_environ[wsgikey] = value
1308
1309 self.environ.update(ssl_environ)
1310