1 """Generic socket server classes.
3 This module tries to capture the various aspects of defining a server:
5 For socket-based servers:
8 - AF_INET{,6}: IP (Internet Protocol) sockets (default)
9 - AF_UNIX: Unix domain sockets
10 - others, e.g. AF_DECNET are conceivable (see <socket.h>
12 - SOCK_STREAM (reliable stream, e.g. TCP)
13 - SOCK_DGRAM (datagrams, e.g. UDP)
15 For request-based servers (including socket-based):
17 - client address verification before further looking at the request
18 (This is actually a hook for any processing that needs to look
19 at the request before anything else, e.g. logging)
20 - how to handle multiple requests:
21 - synchronous (one request is handled at a time)
22 - forking (each request is handled by a new process)
23 - threading (each request is handled by a new thread)
25 The classes in this module favor the server type that is simplest to
26 write: a synchronous TCP/IP server. This is bad class design, but
27 save some typing. (There's also the issue that a deep class hierarchy
28 slows down method lookups.)
30 There are five classes in an inheritance diagram, four of which represent
31 synchronous servers of four types:
38 +-----------+ +------------------+
39 | TCPServer |------->| UnixStreamServer |
40 +-----------+ +------------------+
43 +-----------+ +--------------------+
44 | UDPServer |------->| UnixDatagramServer |
45 +-----------+ +--------------------+
47 Note that UnixDatagramServer derives from UDPServer, not from
48 UnixStreamServer -- the only difference between an IP and a Unix
49 stream server is the address family, which is simply repeated in both
52 Forking and threading versions of each type of server can be created
53 using the ForkingServer and ThreadingServer mix-in classes. For
54 instance, a threading UDP server class is created as follows:
56 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
58 The Mix-in class must come first, since it overrides a method defined
61 To implement a service, you must derive a class from
62 BaseRequestHandler and redefine its handle() method. You can then run
63 various versions of the service by combining one of the server classes
64 with your request handler class.
66 The request handler class must be different for datagram or stream
67 services. This can be hidden by using the mix-in request handler
68 classes StreamRequestHandler or DatagramRequestHandler.
70 Of course, you still have to use your head!
72 For instance, it makes no sense to use a forking server if the service
73 contains state in memory that can be modified by requests (since the
74 modifications in the child process would never reach the initial state
75 kept in the parent process and passed to each child). In this case,
76 you can use a threading server, but you will probably have to use
77 locks to avoid two requests that come in nearly simultaneous to apply
78 conflicting changes to the server state.
80 On the other hand, if you are building e.g. an HTTP server, where all
81 data is stored externally (e.g. in the file system), a synchronous
82 class will essentially render the service "deaf" while one request is
83 being handled -- which may be for a very long time if a client is slow
84 to reqd all the data it has requested. Here a threading or forking
85 server is appropriate.
87 In some cases, it may be appropriate to process part of a request
88 synchronously, but to finish processing in a forked child depending on
89 the request data. This can be implemented by using a synchronous
90 server and doing an explicit fork in the request handler class
93 Another approach to handling multiple simultaneous requests in an
94 environment that supports neither threads nor fork (or where these are
95 too expensive or inappropriate for the service) is to maintain an
96 explicit table of partially finished requests and to use select() to
97 decide which request to work on next (or whether to handle a new
98 incoming request). This is particularly important for stream services
99 where each client can potentially be connected for a long time (if
100 threads or subprocesses cannot be used).
103 - Standard classes for Sun RPC (which uses either UDP or TCP)
104 - Standard mix-in classes to implement various authentication
105 and encryption schemes
106 - Standard framework for select-based multiplexing
109 - What to do with out-of-band data?
112 - split generic "request" functionality out into BaseServer class.
113 Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
115 example: read entries from a SQL database (requires overriding
116 get_request() to return a table entry from the database).
117 entry is processed by a RequestHandlerClass.
135 __all__ = [
"TCPServer",
"UDPServer",
"ForkingUDPServer",
"ForkingTCPServer",
136 "ThreadingUDPServer",
"ThreadingTCPServer",
"BaseRequestHandler",
137 "StreamRequestHandler",
"DatagramRequestHandler",
138 "ThreadingMixIn",
"ForkingMixIn"]
139 if hasattr(socket,
"AF_UNIX"):
140 __all__.extend([
"UnixStreamServer",
"UnixDatagramServer",
141 "ThreadingUnixStreamServer",
142 "ThreadingUnixDatagramServer"])
146 """Base class for server classes.
148 Methods for the caller:
150 - __init__(server_address, RequestHandlerClass)
152 - handle_request() # if you do not use serve_forever()
153 - fileno() -> int # for select()
155 Methods that may be overridden:
159 - get_request() -> request, client_address
160 - verify_request(request, client_address)
162 - process_request(request, client_address)
163 - close_request(request)
166 Methods for derived classes:
168 - finish_request(request, client_address)
170 Class variables that may be overridden by derived classes or
179 - RequestHandlerClass
184 def __init__(self, server_address, RequestHandlerClass):
185 """Constructor. May be extended, do not override."""
190 """Called by constructor to activate the server.
198 """Handle one request at a time until doomsday."""
200 self.handle_request()
214 """Handle one request, possibly blocking."""
216 request, client_address = self.get_request()
227 """Verify the request. May be overridden.
229 Return true if we should proceed with this request.
235 """Call finish_request.
237 Overridden by ForkingMixIn and ThreadingMixIn.
244 """Called to clean-up the server.
252 """Finish one request by instantiating RequestHandlerClass."""
253 self.RequestHandlerClass(request, client_address, self)
256 """Called to clean up an individual request."""
260 """Handle an error gracefully. May be overridden.
262 The default is to print a traceback and continue.
266 print 'Exception happened during processing of request from',
275 """Base class for various socket-based server classes.
277 Defaults to synchronous IP stream (i.e., TCP).
279 Methods for the caller:
281 - __init__(server_address, RequestHandlerClass)
283 - handle_request() # if you don't use serve_forever()
284 - fileno() -> int # for select()
286 Methods that may be overridden:
290 - get_request() -> request, client_address
291 - verify_request(request, client_address)
292 - process_request(request, client_address)
293 - close_request(request)
296 Methods for derived classes:
298 - finish_request(request, client_address)
300 Class variables that may be overridden by derived classes or
305 - request_queue_size (only for stream sockets)
311 - RequestHandlerClass
316 address_family = socket.AF_INET
318 socket_type = socket.SOCK_STREAM
320 request_queue_size = 5
322 allow_reuse_address = 0
324 def __init__(self, server_address, RequestHandlerClass):
325 """Constructor. May be extended, do not override."""
326 BaseServer.__init__(self, server_address, RequestHandlerClass)
333 """Called by constructor to bind the socket.
339 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
343 """Called by constructor to activate the server.
351 """Called to clean-up the server.
359 """Return socket file number.
361 Interface required by select().
364 return self.socket.fileno()
367 """Get the request and client address from the socket.
372 return self.socket.accept()
375 """Called to clean up an individual request."""
381 """UDP server class."""
383 allow_reuse_address = 0
385 socket_type = socket.SOCK_DGRAM
387 max_packet_size = 8192
391 return (data, self.
socket), client_addr
403 """Mix-in class to handle each request in a new process."""
405 active_children =
None
409 """Internal routine to wait for died children."""
418 pid, status = os.waitpid(0, options)
422 self.active_children.remove(pid)
425 """Fork a new subprocess to process the request."""
432 self.active_children.append(pid)
433 self.close_request(request)
439 self.finish_request(request, client_address)
443 self.handle_error(request, client_address)
449 """Mix-in class to handle each request in a new thread."""
452 """Same as in BaseServer but as a thread.
454 In addition, exception handling is done here.
458 self.finish_request(request, client_address)
459 self.close_request(request)
461 self.handle_error(request, client_address)
462 self.close_request(request)
465 """Start a new thread to process the request."""
468 args = (request, client_address))
478 if hasattr(socket,
'AF_UNIX'):
481 address_family = socket.AF_UNIX
484 address_family = socket.AF_UNIX
492 """Base class for request handler classes.
494 This class is instantiated for each request to be handled. The
495 constructor sets the instance variables request, client_address
496 and server, and then calls the handle() method. To implement a
497 specific service, all you need to do is to derive a class which
498 defines a handle() method.
500 The handle() method can find the request as self.request, the
501 client address as self.client_address, and the server (in case it
502 needs access to per-server information) as self.server. Since a
503 separate instance is created for each request, the handle() method
504 can define arbitrary other instance variariables.
508 def __init__(self, request, client_address, server):
517 sys.exc_traceback =
None
537 class StreamRequestHandler(BaseRequestHandler):
539 """Define self.rfile and self.wfile for stream sockets."""
567 """Define self.rfile and self.wfile for datagram sockets."""