Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 1 | """Generic socket server classes. |
| 2 | |
| 3 | This module tries to capture the various aspects of defining a server: |
| 4 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 5 | For socket-based servers: |
| 6 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 7 | - address family: |
Martin v. Löwis | a43c2f8 | 2001-07-24 20:34:08 +0000 | [diff] [blame] | 8 | - AF_INET{,6}: IP (Internet Protocol) sockets (default) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 9 | - AF_UNIX: Unix domain sockets |
| 10 | - others, e.g. AF_DECNET are conceivable (see <socket.h> |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 11 | - socket type: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 12 | - SOCK_STREAM (reliable stream, e.g. TCP) |
| 13 | - SOCK_DGRAM (datagrams, e.g. UDP) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 14 | |
| 15 | For request-based servers (including socket-based): |
| 16 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 17 | - client address verification before further looking at the request |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 18 | (This is actually a hook for any processing that needs to look |
| 19 | at the request before anything else, e.g. logging) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 20 | - how to handle multiple requests: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 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) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 24 | |
| 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.) |
| 29 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 30 | There are five classes in an inheritance diagram, four of which represent |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 31 | synchronous servers of four types: |
| 32 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 33 | +------------+ |
| 34 | | BaseServer | |
| 35 | +------------+ |
| 36 | | |
| 37 | v |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 38 | +-----------+ +------------------+ |
| 39 | | TCPServer |------->| UnixStreamServer | |
| 40 | +-----------+ +------------------+ |
| 41 | | |
| 42 | v |
| 43 | +-----------+ +--------------------+ |
| 44 | | UDPServer |------->| UnixDatagramServer | |
| 45 | +-----------+ +--------------------+ |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 46 | |
Guido van Rossum | db2b70c | 1997-07-16 16:21:38 +0000 | [diff] [blame] | 47 | Note that UnixDatagramServer derives from UDPServer, not from |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 48 | UnixStreamServer -- the only difference between an IP and a Unix |
| 49 | stream server is the address family, which is simply repeated in both |
Guido van Rossum | db2b70c | 1997-07-16 16:21:38 +0000 | [diff] [blame] | 50 | unix server classes. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 51 | |
| 52 | Forking and threading versions of each type of server can be created |
Guido van Rossum | ebbffd4 | 2005-04-30 00:20:35 +0000 | [diff] [blame] | 53 | using the ForkingMixIn and ThreadingMixIn mix-in classes. For |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 54 | instance, a threading UDP server class is created as follows: |
| 55 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 56 | class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 57 | |
Guido van Rossum | db2b70c | 1997-07-16 16:21:38 +0000 | [diff] [blame] | 58 | The Mix-in class must come first, since it overrides a method defined |
Martin v. Löwis | f86e8ef | 2002-11-22 08:08:44 +0000 | [diff] [blame] | 59 | in UDPServer! Setting the various member variables also changes |
| 60 | the behavior of the underlying server mechanism. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 61 | |
| 62 | To implement a service, you must derive a class from |
| 63 | BaseRequestHandler and redefine its handle() method. You can then run |
| 64 | various versions of the service by combining one of the server classes |
| 65 | with your request handler class. |
| 66 | |
| 67 | The request handler class must be different for datagram or stream |
Georg Brandl | ca5feab | 2005-07-18 07:38:44 +0000 | [diff] [blame] | 68 | services. This can be hidden by using the request handler |
| 69 | subclasses StreamRequestHandler or DatagramRequestHandler. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 70 | |
| 71 | Of course, you still have to use your head! |
| 72 | |
| 73 | For instance, it makes no sense to use a forking server if the service |
| 74 | contains state in memory that can be modified by requests (since the |
| 75 | modifications in the child process would never reach the initial state |
| 76 | kept in the parent process and passed to each child). In this case, |
| 77 | you can use a threading server, but you will probably have to use |
| 78 | locks to avoid two requests that come in nearly simultaneous to apply |
| 79 | conflicting changes to the server state. |
| 80 | |
| 81 | On the other hand, if you are building e.g. an HTTP server, where all |
| 82 | data is stored externally (e.g. in the file system), a synchronous |
| 83 | class will essentially render the service "deaf" while one request is |
| 84 | being handled -- which may be for a very long time if a client is slow |
Ezio Melotti | f78869e | 2011-10-29 10:41:51 +0300 | [diff] [blame] | 85 | to read all the data it has requested. Here a threading or forking |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 86 | server is appropriate. |
| 87 | |
| 88 | In some cases, it may be appropriate to process part of a request |
| 89 | synchronously, but to finish processing in a forked child depending on |
| 90 | the request data. This can be implemented by using a synchronous |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 91 | server and doing an explicit fork in the request handler class |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 92 | handle() method. |
| 93 | |
| 94 | Another approach to handling multiple simultaneous requests in an |
| 95 | environment that supports neither threads nor fork (or where these are |
| 96 | too expensive or inappropriate for the service) is to maintain an |
| 97 | explicit table of partially finished requests and to use select() to |
| 98 | decide which request to work on next (or whether to handle a new |
| 99 | incoming request). This is particularly important for stream services |
| 100 | where each client can potentially be connected for a long time (if |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 101 | threads or subprocesses cannot be used). |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 102 | |
| 103 | Future work: |
| 104 | - Standard classes for Sun RPC (which uses either UDP or TCP) |
| 105 | - Standard mix-in classes to implement various authentication |
| 106 | and encryption schemes |
| 107 | - Standard framework for select-based multiplexing |
| 108 | |
| 109 | XXX Open problems: |
| 110 | - What to do with out-of-band data? |
| 111 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 112 | BaseServer: |
| 113 | - split generic "request" functionality out into BaseServer class. |
| 114 | Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org> |
| 115 | |
| 116 | example: read entries from a SQL database (requires overriding |
| 117 | get_request() to return a table entry from the database). |
| 118 | entry is processed by a RequestHandlerClass. |
| 119 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 120 | """ |
| 121 | |
Guido van Rossum | 10b0418 | 2001-01-19 16:45:46 +0000 | [diff] [blame] | 122 | # Author of the BaseServer patch: Luke Kenneth Casson Leighton |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 123 | |
Guido van Rossum | 7de4d64 | 2001-07-10 11:50:09 +0000 | [diff] [blame] | 124 | # XXX Warning! |
| 125 | # There is a test suite for this module, but it cannot be run by the |
| 126 | # standard regression test. |
| 127 | # To run it manually, run Lib/test/test_socketserver.py. |
| 128 | |
| 129 | __version__ = "0.4" |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 130 | |
| 131 | |
| 132 | import socket |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 133 | import select |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 134 | import sys |
| 135 | import os |
Antoine Pitrou | b0a9c66 | 2012-04-09 00:47:24 +0200 | [diff] [blame] | 136 | import errno |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 137 | try: |
| 138 | import threading |
| 139 | except ImportError: |
| 140 | import dummy_threading as threading |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 141 | |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 142 | __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", |
| 143 | "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler", |
Guido van Rossum | 7de4d64 | 2001-07-10 11:50:09 +0000 | [diff] [blame] | 144 | "StreamRequestHandler","DatagramRequestHandler", |
| 145 | "ThreadingMixIn", "ForkingMixIn"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 146 | if hasattr(socket, "AF_UNIX"): |
| 147 | __all__.extend(["UnixStreamServer","UnixDatagramServer", |
| 148 | "ThreadingUnixStreamServer", |
| 149 | "ThreadingUnixDatagramServer"]) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 150 | |
Antoine Pitrou | b0a9c66 | 2012-04-09 00:47:24 +0200 | [diff] [blame] | 151 | def _eintr_retry(func, *args): |
| 152 | """restart a system call interrupted by EINTR""" |
| 153 | while True: |
| 154 | try: |
| 155 | return func(*args) |
Antoine Pitrou | c0aa9ee | 2012-04-09 01:37:19 +0200 | [diff] [blame] | 156 | except (OSError, select.error) as e: |
| 157 | if e.args[0] != errno.EINTR: |
Antoine Pitrou | b0a9c66 | 2012-04-09 00:47:24 +0200 | [diff] [blame] | 158 | raise |
| 159 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 160 | class BaseServer: |
| 161 | |
| 162 | """Base class for server classes. |
| 163 | |
| 164 | Methods for the caller: |
| 165 | |
| 166 | - __init__(server_address, RequestHandlerClass) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 167 | - serve_forever(poll_interval=0.5) |
| 168 | - shutdown() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 169 | - handle_request() # if you do not use serve_forever() |
| 170 | - fileno() -> int # for select() |
| 171 | |
| 172 | Methods that may be overridden: |
| 173 | |
| 174 | - server_bind() |
| 175 | - server_activate() |
| 176 | - get_request() -> request, client_address |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 177 | - handle_timeout() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 178 | - verify_request(request, client_address) |
| 179 | - server_close() |
| 180 | - process_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 181 | - shutdown_request(request) |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 182 | - close_request(request) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 183 | - handle_error() |
| 184 | |
| 185 | Methods for derived classes: |
| 186 | |
| 187 | - finish_request(request, client_address) |
| 188 | |
| 189 | Class variables that may be overridden by derived classes or |
| 190 | instances: |
| 191 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 192 | - timeout |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 193 | - address_family |
| 194 | - socket_type |
Barry Warsaw | b97f0b7 | 2003-10-09 23:48:52 +0000 | [diff] [blame] | 195 | - allow_reuse_address |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 196 | |
| 197 | Instance variables: |
| 198 | |
| 199 | - RequestHandlerClass |
| 200 | - socket |
| 201 | |
| 202 | """ |
| 203 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 204 | timeout = None |
| 205 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 206 | def __init__(self, server_address, RequestHandlerClass): |
| 207 | """Constructor. May be extended, do not override.""" |
| 208 | self.server_address = server_address |
| 209 | self.RequestHandlerClass = RequestHandlerClass |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 210 | self.__is_shut_down = threading.Event() |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 211 | self.__shutdown_request = False |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 212 | |
| 213 | def server_activate(self): |
| 214 | """Called by constructor to activate the server. |
| 215 | |
| 216 | May be overridden. |
| 217 | |
| 218 | """ |
| 219 | pass |
| 220 | |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 221 | def serve_forever(self, poll_interval=0.5): |
| 222 | """Handle one request at a time until shutdown. |
| 223 | |
| 224 | Polls for shutdown every poll_interval seconds. Ignores |
| 225 | self.timeout. If you need to do periodic tasks, do them in |
| 226 | another thread. |
| 227 | """ |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 228 | self.__is_shut_down.clear() |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 229 | try: |
| 230 | while not self.__shutdown_request: |
| 231 | # XXX: Consider using another file descriptor or |
| 232 | # connecting to the socket to wake this up instead of |
| 233 | # polling. Polling reduces our responsiveness to a |
| 234 | # shutdown request and wastes cpu at all other times. |
Antoine Pitrou | b0a9c66 | 2012-04-09 00:47:24 +0200 | [diff] [blame] | 235 | r, w, e = _eintr_retry(select.select, [self], [], [], |
| 236 | poll_interval) |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 237 | if self in r: |
| 238 | self._handle_request_noblock() |
| 239 | finally: |
| 240 | self.__shutdown_request = False |
| 241 | self.__is_shut_down.set() |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 242 | |
| 243 | def shutdown(self): |
| 244 | """Stops the serve_forever loop. |
| 245 | |
| 246 | Blocks until the loop has finished. This must be called while |
| 247 | serve_forever() is running in another thread, or it will |
| 248 | deadlock. |
| 249 | """ |
Antoine Pitrou | 3bcba8e | 2010-04-25 22:01:43 +0000 | [diff] [blame] | 250 | self.__shutdown_request = True |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 251 | self.__is_shut_down.wait() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 252 | |
| 253 | # The distinction between handling, getting, processing and |
| 254 | # finishing a request is fairly arbitrary. Remember: |
| 255 | # |
| 256 | # - handle_request() is the top-level call. It calls |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 257 | # select, get_request(), verify_request() and process_request() |
| 258 | # - get_request() is different for stream or datagram sockets |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 259 | # - process_request() is the place that may fork a new process |
| 260 | # or create a new thread to finish the request |
| 261 | # - finish_request() instantiates the request handler class; |
| 262 | # this constructor will handle the request all by itself |
| 263 | |
| 264 | def handle_request(self): |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 265 | """Handle one request, possibly blocking. |
| 266 | |
| 267 | Respects self.timeout. |
| 268 | """ |
| 269 | # Support people who used socket.settimeout() to escape |
| 270 | # handle_request before self.timeout was available. |
| 271 | timeout = self.socket.gettimeout() |
| 272 | if timeout is None: |
| 273 | timeout = self.timeout |
| 274 | elif self.timeout is not None: |
| 275 | timeout = min(timeout, self.timeout) |
Antoine Pitrou | b0a9c66 | 2012-04-09 00:47:24 +0200 | [diff] [blame] | 276 | fd_sets = _eintr_retry(select.select, [self], [], [], timeout) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 277 | if not fd_sets[0]: |
| 278 | self.handle_timeout() |
| 279 | return |
| 280 | self._handle_request_noblock() |
| 281 | |
| 282 | def _handle_request_noblock(self): |
| 283 | """Handle one request, without blocking. |
| 284 | |
| 285 | I assume that select.select has returned that the socket is |
| 286 | readable before this function was called, so there should be |
| 287 | no risk of blocking in get_request(). |
| 288 | """ |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 289 | try: |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 290 | request, client_address = self.get_request() |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 291 | except socket.error: |
| 292 | return |
| 293 | if self.verify_request(request, client_address): |
| 294 | try: |
| 295 | self.process_request(request, client_address) |
| 296 | except: |
| 297 | self.handle_error(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 298 | self.shutdown_request(request) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 299 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 300 | def handle_timeout(self): |
| 301 | """Called if no new request arrives within self.timeout. |
| 302 | |
| 303 | Overridden by ForkingMixIn. |
| 304 | """ |
| 305 | pass |
| 306 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 307 | def verify_request(self, request, client_address): |
| 308 | """Verify the request. May be overridden. |
| 309 | |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 310 | Return True if we should proceed with this request. |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 311 | |
| 312 | """ |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 313 | return True |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 314 | |
| 315 | def process_request(self, request, client_address): |
| 316 | """Call finish_request. |
| 317 | |
| 318 | Overridden by ForkingMixIn and ThreadingMixIn. |
| 319 | |
| 320 | """ |
| 321 | self.finish_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 322 | self.shutdown_request(request) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 323 | |
| 324 | def server_close(self): |
| 325 | """Called to clean-up the server. |
| 326 | |
| 327 | May be overridden. |
| 328 | |
| 329 | """ |
| 330 | pass |
| 331 | |
| 332 | def finish_request(self, request, client_address): |
| 333 | """Finish one request by instantiating RequestHandlerClass.""" |
| 334 | self.RequestHandlerClass(request, client_address, self) |
| 335 | |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 336 | def shutdown_request(self, request): |
| 337 | """Called to shutdown and close an individual request.""" |
| 338 | self.close_request(request) |
| 339 | |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 340 | def close_request(self, request): |
| 341 | """Called to clean up an individual request.""" |
| 342 | pass |
| 343 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 344 | def handle_error(self, request, client_address): |
| 345 | """Handle an error gracefully. May be overridden. |
| 346 | |
| 347 | The default is to print a traceback and continue. |
| 348 | |
| 349 | """ |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 350 | print('-'*40) |
| 351 | print('Exception happened during processing of request from', end=' ') |
| 352 | print(client_address) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 353 | import traceback |
| 354 | traceback.print_exc() # XXX But this goes to stderr! |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 355 | print('-'*40) |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 356 | |
| 357 | |
| 358 | class TCPServer(BaseServer): |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 359 | |
| 360 | """Base class for various socket-based server classes. |
| 361 | |
| 362 | Defaults to synchronous IP stream (i.e., TCP). |
| 363 | |
| 364 | Methods for the caller: |
| 365 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 366 | - __init__(server_address, RequestHandlerClass, bind_and_activate=True) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 367 | - serve_forever(poll_interval=0.5) |
| 368 | - shutdown() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 369 | - handle_request() # if you don't use serve_forever() |
| 370 | - fileno() -> int # for select() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 371 | |
| 372 | Methods that may be overridden: |
| 373 | |
| 374 | - server_bind() |
| 375 | - server_activate() |
| 376 | - get_request() -> request, client_address |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 377 | - handle_timeout() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 378 | - verify_request(request, client_address) |
| 379 | - process_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 380 | - shutdown_request(request) |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 381 | - close_request(request) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 382 | - handle_error() |
| 383 | |
| 384 | Methods for derived classes: |
| 385 | |
| 386 | - finish_request(request, client_address) |
| 387 | |
| 388 | Class variables that may be overridden by derived classes or |
| 389 | instances: |
| 390 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 391 | - timeout |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 392 | - address_family |
| 393 | - socket_type |
| 394 | - request_queue_size (only for stream sockets) |
Barry Warsaw | 3aaad50 | 2003-10-09 22:44:05 +0000 | [diff] [blame] | 395 | - allow_reuse_address |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 396 | |
| 397 | Instance variables: |
| 398 | |
| 399 | - server_address |
| 400 | - RequestHandlerClass |
| 401 | - socket |
| 402 | |
| 403 | """ |
| 404 | |
| 405 | address_family = socket.AF_INET |
| 406 | |
| 407 | socket_type = socket.SOCK_STREAM |
| 408 | |
| 409 | request_queue_size = 5 |
| 410 | |
Raymond Hettinger | c8f8034 | 2002-08-25 16:36:49 +0000 | [diff] [blame] | 411 | allow_reuse_address = False |
Guido van Rossum | e3c7a5f | 2000-05-09 14:53:29 +0000 | [diff] [blame] | 412 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 413 | def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 414 | """Constructor. May be extended, do not override.""" |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 415 | BaseServer.__init__(self, server_address, RequestHandlerClass) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 416 | self.socket = socket.socket(self.address_family, |
| 417 | self.socket_type) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 418 | if bind_and_activate: |
| 419 | self.server_bind() |
| 420 | self.server_activate() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 421 | |
| 422 | def server_bind(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 423 | """Called by constructor to bind the socket. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 424 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 425 | May be overridden. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 426 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 427 | """ |
Guido van Rossum | e3c7a5f | 2000-05-09 14:53:29 +0000 | [diff] [blame] | 428 | if self.allow_reuse_address: |
| 429 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 430 | self.socket.bind(self.server_address) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 431 | self.server_address = self.socket.getsockname() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 432 | |
| 433 | def server_activate(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 434 | """Called by constructor to activate the server. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 435 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 436 | May be overridden. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 437 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 438 | """ |
| 439 | self.socket.listen(self.request_queue_size) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 440 | |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 441 | def server_close(self): |
| 442 | """Called to clean-up the server. |
| 443 | |
| 444 | May be overridden. |
| 445 | |
| 446 | """ |
| 447 | self.socket.close() |
| 448 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 449 | def fileno(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 450 | """Return socket file number. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 451 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 452 | Interface required by select(). |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 453 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 454 | """ |
| 455 | return self.socket.fileno() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 456 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 457 | def get_request(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 458 | """Get the request and client address from the socket. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 459 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 460 | May be overridden. |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 461 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 462 | """ |
| 463 | return self.socket.accept() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 464 | |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 465 | def shutdown_request(self, request): |
| 466 | """Called to shutdown and close an individual request.""" |
Kristján Valur Jónsson | 200cfd0 | 2009-07-04 15:18:00 +0000 | [diff] [blame] | 467 | try: |
| 468 | #explicitly shutdown. socket.close() merely releases |
| 469 | #the socket and waits for GC to perform the actual close. |
| 470 | request.shutdown(socket.SHUT_WR) |
| 471 | except socket.error: |
| 472 | pass #some platforms may raise ENOTCONN here |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 473 | self.close_request(request) |
| 474 | |
| 475 | def close_request(self, request): |
| 476 | """Called to clean up an individual request.""" |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 477 | request.close() |
| 478 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 479 | |
| 480 | class UDPServer(TCPServer): |
| 481 | |
| 482 | """UDP server class.""" |
| 483 | |
Raymond Hettinger | c8f8034 | 2002-08-25 16:36:49 +0000 | [diff] [blame] | 484 | allow_reuse_address = False |
Guido van Rossum | 90cb906 | 2001-01-19 00:44:41 +0000 | [diff] [blame] | 485 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 486 | socket_type = socket.SOCK_DGRAM |
| 487 | |
| 488 | max_packet_size = 8192 |
| 489 | |
| 490 | def get_request(self): |
Guido van Rossum | 3249082 | 1998-06-16 02:27:33 +0000 | [diff] [blame] | 491 | data, client_addr = self.socket.recvfrom(self.max_packet_size) |
| 492 | return (data, self.socket), client_addr |
| 493 | |
| 494 | def server_activate(self): |
| 495 | # No need to call listen() for UDP. |
| 496 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 497 | |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 498 | def shutdown_request(self, request): |
| 499 | # No need to shutdown anything. |
| 500 | self.close_request(request) |
| 501 | |
Ka-Ping Yee | 285a7e5 | 2001-04-11 04:02:05 +0000 | [diff] [blame] | 502 | def close_request(self, request): |
| 503 | # No need to close anything. |
| 504 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 505 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 506 | class ForkingMixIn: |
| 507 | |
| 508 | """Mix-in class to handle each request in a new process.""" |
| 509 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 510 | timeout = 300 |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 511 | active_children = None |
Guido van Rossum | 2ab455a | 1999-07-28 21:39:28 +0000 | [diff] [blame] | 512 | max_children = 40 |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 513 | |
| 514 | def collect_children(self): |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 515 | """Internal routine to wait for children that have exited.""" |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 516 | if self.active_children is None: return |
| 517 | while len(self.active_children) >= self.max_children: |
| 518 | # XXX: This will wait for any child process, not just ones |
| 519 | # spawned by this library. This could confuse other |
| 520 | # libraries that expect to be able to wait for their own |
| 521 | # children. |
Guido van Rossum | bfadac0 | 1999-06-17 15:41:33 +0000 | [diff] [blame] | 522 | try: |
Benjamin Peterson | ad3d5c2 | 2009-02-26 03:38:59 +0000 | [diff] [blame] | 523 | pid, status = os.waitpid(0, 0) |
Guido van Rossum | bfadac0 | 1999-06-17 15:41:33 +0000 | [diff] [blame] | 524 | except os.error: |
| 525 | pid = None |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 526 | if pid not in self.active_children: continue |
| 527 | self.active_children.remove(pid) |
| 528 | |
| 529 | # XXX: This loop runs more system calls than it ought |
| 530 | # to. There should be a way to put the active_children into a |
| 531 | # process group and then use os.waitpid(-pgid) to wait for any |
| 532 | # of that set, but I couldn't find a way to allocate pgids |
| 533 | # that couldn't collide. |
| 534 | for child in self.active_children: |
| 535 | try: |
| 536 | pid, status = os.waitpid(child, os.WNOHANG) |
| 537 | except os.error: |
| 538 | pid = None |
| 539 | if not pid: continue |
Christian Heimes | a156e09 | 2008-02-16 07:38:31 +0000 | [diff] [blame] | 540 | try: |
| 541 | self.active_children.remove(pid) |
| 542 | except ValueError as e: |
| 543 | raise ValueError('%s. x=%d and list=%r' % (e.message, pid, |
| 544 | self.active_children)) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 545 | |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 546 | def handle_timeout(self): |
| 547 | """Wait for zombies after self.timeout seconds of inactivity. |
| 548 | |
| 549 | May be extended, do not override. |
| 550 | """ |
| 551 | self.collect_children() |
| 552 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 553 | def process_request(self, request, client_address): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 554 | """Fork a new subprocess to process the request.""" |
| 555 | self.collect_children() |
| 556 | pid = os.fork() |
| 557 | if pid: |
| 558 | # Parent process |
| 559 | if self.active_children is None: |
| 560 | self.active_children = [] |
| 561 | self.active_children.append(pid) |
Guido van Rossum | 7de4d64 | 2001-07-10 11:50:09 +0000 | [diff] [blame] | 562 | self.close_request(request) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 563 | else: |
| 564 | # Child process. |
| 565 | # This must never return, hence os._exit()! |
| 566 | try: |
| 567 | self.finish_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 568 | self.shutdown_request(request) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 569 | os._exit(0) |
| 570 | except: |
| 571 | try: |
Guido van Rossum | 7de4d64 | 2001-07-10 11:50:09 +0000 | [diff] [blame] | 572 | self.handle_error(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 573 | self.shutdown_request(request) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 574 | finally: |
| 575 | os._exit(1) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 576 | |
| 577 | |
| 578 | class ThreadingMixIn: |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 579 | """Mix-in class to handle each request in a new thread.""" |
| 580 | |
Martin v. Löwis | f86e8ef | 2002-11-22 08:08:44 +0000 | [diff] [blame] | 581 | # Decides how threads will act upon termination of the |
| 582 | # main process |
Fred Drake | 132e0e8 | 2002-11-22 14:22:49 +0000 | [diff] [blame] | 583 | daemon_threads = False |
Martin v. Löwis | f86e8ef | 2002-11-22 08:08:44 +0000 | [diff] [blame] | 584 | |
Guido van Rossum | a5343cc | 2001-10-18 18:02:07 +0000 | [diff] [blame] | 585 | def process_request_thread(self, request, client_address): |
Guido van Rossum | 83c3281 | 2001-10-23 21:42:45 +0000 | [diff] [blame] | 586 | """Same as in BaseServer but as a thread. |
| 587 | |
| 588 | In addition, exception handling is done here. |
| 589 | |
| 590 | """ |
| 591 | try: |
| 592 | self.finish_request(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 593 | self.shutdown_request(request) |
Guido van Rossum | 83c3281 | 2001-10-23 21:42:45 +0000 | [diff] [blame] | 594 | except: |
| 595 | self.handle_error(request, client_address) |
Kristján Valur Jónsson | a5b47ce | 2009-07-07 09:09:10 +0000 | [diff] [blame] | 596 | self.shutdown_request(request) |
Guido van Rossum | a5343cc | 2001-10-18 18:02:07 +0000 | [diff] [blame] | 597 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 598 | def process_request(self, request, client_address): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 599 | """Start a new thread to process the request.""" |
Guido van Rossum | a5343cc | 2001-10-18 18:02:07 +0000 | [diff] [blame] | 600 | t = threading.Thread(target = self.process_request_thread, |
Jeremy Hylton | 7526027 | 1999-10-12 16:20:13 +0000 | [diff] [blame] | 601 | args = (request, client_address)) |
Florent Xicluna | 12b66b5 | 2011-11-04 10:16:28 +0100 | [diff] [blame] | 602 | t.daemon = self.daemon_threads |
Jeremy Hylton | 7526027 | 1999-10-12 16:20:13 +0000 | [diff] [blame] | 603 | t.start() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 604 | |
| 605 | |
| 606 | class ForkingUDPServer(ForkingMixIn, UDPServer): pass |
| 607 | class ForkingTCPServer(ForkingMixIn, TCPServer): pass |
| 608 | |
| 609 | class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass |
| 610 | class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass |
| 611 | |
Guido van Rossum | 67a40e8 | 1998-11-30 15:07:01 +0000 | [diff] [blame] | 612 | if hasattr(socket, 'AF_UNIX'): |
| 613 | |
| 614 | class UnixStreamServer(TCPServer): |
| 615 | address_family = socket.AF_UNIX |
| 616 | |
| 617 | class UnixDatagramServer(UDPServer): |
| 618 | address_family = socket.AF_UNIX |
| 619 | |
| 620 | class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass |
| 621 | |
| 622 | class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 623 | |
| 624 | class BaseRequestHandler: |
| 625 | |
| 626 | """Base class for request handler classes. |
| 627 | |
| 628 | This class is instantiated for each request to be handled. The |
| 629 | constructor sets the instance variables request, client_address |
| 630 | and server, and then calls the handle() method. To implement a |
| 631 | specific service, all you need to do is to derive a class which |
| 632 | defines a handle() method. |
| 633 | |
| 634 | The handle() method can find the request as self.request, the |
Guido van Rossum | fdb3d1a | 1998-11-16 19:06:30 +0000 | [diff] [blame] | 635 | client address as self.client_address, and the server (in case it |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 636 | needs access to per-server information) as self.server. Since a |
| 637 | separate instance is created for each request, the handle() method |
| 638 | can define arbitrary other instance variariables. |
| 639 | |
| 640 | """ |
| 641 | |
| 642 | def __init__(self, request, client_address, server): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 643 | self.request = request |
| 644 | self.client_address = client_address |
| 645 | self.server = server |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 646 | self.setup() |
Kristján Valur Jónsson | 985fc6a | 2009-07-01 10:01:31 +0000 | [diff] [blame] | 647 | try: |
| 648 | self.handle() |
| 649 | finally: |
| 650 | self.finish() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 651 | |
| 652 | def setup(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 653 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 654 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 655 | def handle(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 656 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 657 | |
| 658 | def finish(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 659 | pass |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 660 | |
| 661 | |
| 662 | # The following two classes make it possible to use the same service |
| 663 | # class for stream or datagram servers. |
| 664 | # Each class sets up these instance variables: |
| 665 | # - rfile: a file object from which receives the request is read |
| 666 | # - wfile: a file object to which the reply is written |
| 667 | # When the handle() method returns, wfile is flushed properly |
| 668 | |
| 669 | |
| 670 | class StreamRequestHandler(BaseRequestHandler): |
| 671 | |
| 672 | """Define self.rfile and self.wfile for stream sockets.""" |
| 673 | |
Guido van Rossum | 01fed4d | 2000-09-01 03:25:14 +0000 | [diff] [blame] | 674 | # Default buffer sizes for rfile, wfile. |
| 675 | # We default rfile to buffered because otherwise it could be |
| 676 | # really slow for large data (a getc() call per byte); we make |
| 677 | # wfile unbuffered because (a) often after a write() we want to |
| 678 | # read and we need to flush the line; (b) big writes to unbuffered |
| 679 | # files are typically optimized by stdio even when big reads |
| 680 | # aren't. |
| 681 | rbufsize = -1 |
| 682 | wbufsize = 0 |
| 683 | |
Kristján Valur Jónsson | 985fc6a | 2009-07-01 10:01:31 +0000 | [diff] [blame] | 684 | # A timeout to apply to the request socket, if not None. |
| 685 | timeout = None |
| 686 | |
Ezio Melotti | 4969f70 | 2011-03-15 05:59:46 +0200 | [diff] [blame] | 687 | # Disable nagle algorithm for this socket, if True. |
Kristján Valur Jónsson | 41a5750 | 2009-06-28 21:34:22 +0000 | [diff] [blame] | 688 | # Use only when wbufsize != 0, to avoid small packets. |
| 689 | disable_nagle_algorithm = False |
| 690 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 691 | def setup(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 692 | self.connection = self.request |
Kristján Valur Jónsson | 985fc6a | 2009-07-01 10:01:31 +0000 | [diff] [blame] | 693 | if self.timeout is not None: |
| 694 | self.connection.settimeout(self.timeout) |
Kristján Valur Jónsson | 41a5750 | 2009-06-28 21:34:22 +0000 | [diff] [blame] | 695 | if self.disable_nagle_algorithm: |
| 696 | self.connection.setsockopt(socket.IPPROTO_TCP, |
| 697 | socket.TCP_NODELAY, True) |
Guido van Rossum | 01fed4d | 2000-09-01 03:25:14 +0000 | [diff] [blame] | 698 | self.rfile = self.connection.makefile('rb', self.rbufsize) |
| 699 | self.wfile = self.connection.makefile('wb', self.wbufsize) |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 700 | |
| 701 | def finish(self): |
Anthony Baxter | 4cedc1e | 2003-01-02 03:07:48 +0000 | [diff] [blame] | 702 | if not self.wfile.closed: |
| 703 | self.wfile.flush() |
Guido van Rossum | 1d5102c | 1998-04-03 16:49:52 +0000 | [diff] [blame] | 704 | self.wfile.close() |
| 705 | self.rfile.close() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 706 | |
| 707 | |
| 708 | class DatagramRequestHandler(BaseRequestHandler): |
| 709 | |
Guido van Rossum | 7de4d64 | 2001-07-10 11:50:09 +0000 | [diff] [blame] | 710 | # XXX Regrettably, I cannot get this working on Linux; |
| 711 | # s.recvfrom() doesn't return a meaningful client address. |
| 712 | |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 713 | """Define self.rfile and self.wfile for datagram sockets.""" |
| 714 | |
| 715 | def setup(self): |
Guido van Rossum | 15863ea | 2007-08-03 19:03:39 +0000 | [diff] [blame] | 716 | from io import BytesIO |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 717 | self.packet, self.socket = self.request |
Guido van Rossum | 15863ea | 2007-08-03 19:03:39 +0000 | [diff] [blame] | 718 | self.rfile = BytesIO(self.packet) |
| 719 | self.wfile = BytesIO() |
Guido van Rossum | e7e578f | 1995-08-04 04:00:20 +0000 | [diff] [blame] | 720 | |
| 721 | def finish(self): |
Guido van Rossum | 3249082 | 1998-06-16 02:27:33 +0000 | [diff] [blame] | 722 | self.socket.sendto(self.wfile.getvalue(), self.client_address) |