socketserver.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. """Generic socket server classes.
  2. This module tries to capture the various aspects of defining a server:
  3. For socket-based servers:
  4. - address family:
  5. - AF_INET{,6}: IP (Internet Protocol) sockets (default)
  6. - AF_UNIX: Unix domain sockets
  7. - others, e.g. AF_DECNET are conceivable (see <socket.h>
  8. - socket type:
  9. - SOCK_STREAM (reliable stream, e.g. TCP)
  10. - SOCK_DGRAM (datagrams, e.g. UDP)
  11. For request-based servers (including socket-based):
  12. - client address verification before further looking at the request
  13. (This is actually a hook for any processing that needs to look
  14. at the request before anything else, e.g. logging)
  15. - how to handle multiple requests:
  16. - synchronous (one request is handled at a time)
  17. - forking (each request is handled by a new process)
  18. - threading (each request is handled by a new thread)
  19. The classes in this module favor the server type that is simplest to
  20. write: a synchronous TCP/IP server. This is bad class design, but
  21. saves some typing. (There's also the issue that a deep class hierarchy
  22. slows down method lookups.)
  23. There are five classes in an inheritance diagram, four of which represent
  24. synchronous servers of four types:
  25. +------------+
  26. | BaseServer |
  27. +------------+
  28. |
  29. v
  30. +-----------+ +------------------+
  31. | TCPServer |------->| UnixStreamServer |
  32. +-----------+ +------------------+
  33. |
  34. v
  35. +-----------+ +--------------------+
  36. | UDPServer |------->| UnixDatagramServer |
  37. +-----------+ +--------------------+
  38. Note that UnixDatagramServer derives from UDPServer, not from
  39. UnixStreamServer -- the only difference between an IP and a Unix
  40. stream server is the address family, which is simply repeated in both
  41. unix server classes.
  42. Forking and threading versions of each type of server can be created
  43. using the ForkingMixIn and ThreadingMixIn mix-in classes. For
  44. instance, a threading UDP server class is created as follows:
  45. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  46. The Mix-in class must come first, since it overrides a method defined
  47. in UDPServer! Setting the various member variables also changes
  48. the behavior of the underlying server mechanism.
  49. To implement a service, you must derive a class from
  50. BaseRequestHandler and redefine its handle() method. You can then run
  51. various versions of the service by combining one of the server classes
  52. with your request handler class.
  53. The request handler class must be different for datagram or stream
  54. services. This can be hidden by using the request handler
  55. subclasses StreamRequestHandler or DatagramRequestHandler.
  56. Of course, you still have to use your head!
  57. For instance, it makes no sense to use a forking server if the service
  58. contains state in memory that can be modified by requests (since the
  59. modifications in the child process would never reach the initial state
  60. kept in the parent process and passed to each child). In this case,
  61. you can use a threading server, but you will probably have to use
  62. locks to avoid two requests that come in nearly simultaneous to apply
  63. conflicting changes to the server state.
  64. On the other hand, if you are building e.g. an HTTP server, where all
  65. data is stored externally (e.g. in the file system), a synchronous
  66. class will essentially render the service "deaf" while one request is
  67. being handled -- which may be for a very long time if a client is slow
  68. to read all the data it has requested. Here a threading or forking
  69. server is appropriate.
  70. In some cases, it may be appropriate to process part of a request
  71. synchronously, but to finish processing in a forked child depending on
  72. the request data. This can be implemented by using a synchronous
  73. server and doing an explicit fork in the request handler class
  74. handle() method.
  75. Another approach to handling multiple simultaneous requests in an
  76. environment that supports neither threads nor fork (or where these are
  77. too expensive or inappropriate for the service) is to maintain an
  78. explicit table of partially finished requests and to use a selector to
  79. decide which request to work on next (or whether to handle a new
  80. incoming request). This is particularly important for stream services
  81. where each client can potentially be connected for a long time (if
  82. threads or subprocesses cannot be used).
  83. Future work:
  84. - Standard classes for Sun RPC (which uses either UDP or TCP)
  85. - Standard mix-in classes to implement various authentication
  86. and encryption schemes
  87. XXX Open problems:
  88. - What to do with out-of-band data?
  89. BaseServer:
  90. - split generic "request" functionality out into BaseServer class.
  91. Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
  92. example: read entries from a SQL database (requires overriding
  93. get_request() to return a table entry from the database).
  94. entry is processed by a RequestHandlerClass.
  95. """
  96. # Author of the BaseServer patch: Luke Kenneth Casson Leighton
  97. __version__ = "0.4"
  98. import socket
  99. import selectors
  100. import os
  101. import sys
  102. import threading
  103. from io import BufferedIOBase
  104. from time import monotonic as time
  105. __all__ = ["BaseServer", "TCPServer", "UDPServer",
  106. "ThreadingUDPServer", "ThreadingTCPServer",
  107. "BaseRequestHandler", "StreamRequestHandler",
  108. "DatagramRequestHandler", "ThreadingMixIn"]
  109. if hasattr(os, "fork"):
  110. __all__.extend(["ForkingUDPServer","ForkingTCPServer", "ForkingMixIn"])
  111. if hasattr(socket, "AF_UNIX"):
  112. __all__.extend(["UnixStreamServer","UnixDatagramServer",
  113. "ThreadingUnixStreamServer",
  114. "ThreadingUnixDatagramServer"])
  115. if hasattr(os, "fork"):
  116. __all__.extend(["ForkingUnixStreamServer", "ForkingUnixDatagramServer"])
  117. # poll/select have the advantage of not requiring any extra file descriptor,
  118. # contrarily to epoll/kqueue (also, they require a single syscall).
  119. if hasattr(selectors, 'PollSelector'):
  120. _ServerSelector = selectors.PollSelector
  121. else:
  122. _ServerSelector = selectors.SelectSelector
  123. class BaseServer:
  124. """Base class for server classes.
  125. Methods for the caller:
  126. - __init__(server_address, RequestHandlerClass)
  127. - serve_forever(poll_interval=0.5)
  128. - shutdown()
  129. - handle_request() # if you do not use serve_forever()
  130. - fileno() -> int # for selector
  131. Methods that may be overridden:
  132. - server_bind()
  133. - server_activate()
  134. - get_request() -> request, client_address
  135. - handle_timeout()
  136. - verify_request(request, client_address)
  137. - server_close()
  138. - process_request(request, client_address)
  139. - shutdown_request(request)
  140. - close_request(request)
  141. - service_actions()
  142. - handle_error()
  143. Methods for derived classes:
  144. - finish_request(request, client_address)
  145. Class variables that may be overridden by derived classes or
  146. instances:
  147. - timeout
  148. - address_family
  149. - socket_type
  150. - allow_reuse_address
  151. - allow_reuse_port
  152. Instance variables:
  153. - RequestHandlerClass
  154. - socket
  155. """
  156. timeout = None
  157. def __init__(self, server_address, RequestHandlerClass):
  158. """Constructor. May be extended, do not override."""
  159. self.server_address = server_address
  160. self.RequestHandlerClass = RequestHandlerClass
  161. self.__is_shut_down = threading.Event()
  162. self.__shutdown_request = False
  163. def server_activate(self):
  164. """Called by constructor to activate the server.
  165. May be overridden.
  166. """
  167. pass
  168. def serve_forever(self, poll_interval=0.5):
  169. """Handle one request at a time until shutdown.
  170. Polls for shutdown every poll_interval seconds. Ignores
  171. self.timeout. If you need to do periodic tasks, do them in
  172. another thread.
  173. """
  174. self.__is_shut_down.clear()
  175. try:
  176. # XXX: Consider using another file descriptor or connecting to the
  177. # socket to wake this up instead of polling. Polling reduces our
  178. # responsiveness to a shutdown request and wastes cpu at all other
  179. # times.
  180. with _ServerSelector() as selector:
  181. selector.register(self, selectors.EVENT_READ)
  182. while not self.__shutdown_request:
  183. ready = selector.select(poll_interval)
  184. # bpo-35017: shutdown() called during select(), exit immediately.
  185. if self.__shutdown_request:
  186. break
  187. if ready:
  188. self._handle_request_noblock()
  189. self.service_actions()
  190. finally:
  191. self.__shutdown_request = False
  192. self.__is_shut_down.set()
  193. def shutdown(self):
  194. """Stops the serve_forever loop.
  195. Blocks until the loop has finished. This must be called while
  196. serve_forever() is running in another thread, or it will
  197. deadlock.
  198. """
  199. self.__shutdown_request = True
  200. self.__is_shut_down.wait()
  201. def service_actions(self):
  202. """Called by the serve_forever() loop.
  203. May be overridden by a subclass / Mixin to implement any code that
  204. needs to be run during the loop.
  205. """
  206. pass
  207. # The distinction between handling, getting, processing and finishing a
  208. # request is fairly arbitrary. Remember:
  209. #
  210. # - handle_request() is the top-level call. It calls selector.select(),
  211. # get_request(), verify_request() and process_request()
  212. # - get_request() is different for stream or datagram sockets
  213. # - process_request() is the place that may fork a new process or create a
  214. # new thread to finish the request
  215. # - finish_request() instantiates the request handler class; this
  216. # constructor will handle the request all by itself
  217. def handle_request(self):
  218. """Handle one request, possibly blocking.
  219. Respects self.timeout.
  220. """
  221. # Support people who used socket.settimeout() to escape
  222. # handle_request before self.timeout was available.
  223. timeout = self.socket.gettimeout()
  224. if timeout is None:
  225. timeout = self.timeout
  226. elif self.timeout is not None:
  227. timeout = min(timeout, self.timeout)
  228. if timeout is not None:
  229. deadline = time() + timeout
  230. # Wait until a request arrives or the timeout expires - the loop is
  231. # necessary to accommodate early wakeups due to EINTR.
  232. with _ServerSelector() as selector:
  233. selector.register(self, selectors.EVENT_READ)
  234. while True:
  235. if selector.select(timeout):
  236. return self._handle_request_noblock()
  237. else:
  238. if timeout is not None:
  239. timeout = deadline - time()
  240. if timeout < 0:
  241. return self.handle_timeout()
  242. def _handle_request_noblock(self):
  243. """Handle one request, without blocking.
  244. I assume that selector.select() has returned that the socket is
  245. readable before this function was called, so there should be no risk of
  246. blocking in get_request().
  247. """
  248. try:
  249. request, client_address = self.get_request()
  250. except OSError:
  251. return
  252. if self.verify_request(request, client_address):
  253. try:
  254. self.process_request(request, client_address)
  255. except Exception:
  256. self.handle_error(request, client_address)
  257. self.shutdown_request(request)
  258. except:
  259. self.shutdown_request(request)
  260. raise
  261. else:
  262. self.shutdown_request(request)
  263. def handle_timeout(self):
  264. """Called if no new request arrives within self.timeout.
  265. Overridden by ForkingMixIn.
  266. """
  267. pass
  268. def verify_request(self, request, client_address):
  269. """Verify the request. May be overridden.
  270. Return True if we should proceed with this request.
  271. """
  272. return True
  273. def process_request(self, request, client_address):
  274. """Call finish_request.
  275. Overridden by ForkingMixIn and ThreadingMixIn.
  276. """
  277. self.finish_request(request, client_address)
  278. self.shutdown_request(request)
  279. def server_close(self):
  280. """Called to clean-up the server.
  281. May be overridden.
  282. """
  283. pass
  284. def finish_request(self, request, client_address):
  285. """Finish one request by instantiating RequestHandlerClass."""
  286. self.RequestHandlerClass(request, client_address, self)
  287. def shutdown_request(self, request):
  288. """Called to shutdown and close an individual request."""
  289. self.close_request(request)
  290. def close_request(self, request):
  291. """Called to clean up an individual request."""
  292. pass
  293. def handle_error(self, request, client_address):
  294. """Handle an error gracefully. May be overridden.
  295. The default is to print a traceback and continue.
  296. """
  297. print('-'*40, file=sys.stderr)
  298. print('Exception occurred during processing of request from',
  299. client_address, file=sys.stderr)
  300. import traceback
  301. traceback.print_exc()
  302. print('-'*40, file=sys.stderr)
  303. def __enter__(self):
  304. return self
  305. def __exit__(self, *args):
  306. self.server_close()
  307. class TCPServer(BaseServer):
  308. """Base class for various socket-based server classes.
  309. Defaults to synchronous IP stream (i.e., TCP).
  310. Methods for the caller:
  311. - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
  312. - serve_forever(poll_interval=0.5)
  313. - shutdown()
  314. - handle_request() # if you don't use serve_forever()
  315. - fileno() -> int # for selector
  316. Methods that may be overridden:
  317. - server_bind()
  318. - server_activate()
  319. - get_request() -> request, client_address
  320. - handle_timeout()
  321. - verify_request(request, client_address)
  322. - process_request(request, client_address)
  323. - shutdown_request(request)
  324. - close_request(request)
  325. - handle_error()
  326. Methods for derived classes:
  327. - finish_request(request, client_address)
  328. Class variables that may be overridden by derived classes or
  329. instances:
  330. - timeout
  331. - address_family
  332. - socket_type
  333. - request_queue_size (only for stream sockets)
  334. - allow_reuse_address
  335. - allow_reuse_port
  336. Instance variables:
  337. - server_address
  338. - RequestHandlerClass
  339. - socket
  340. """
  341. address_family = socket.AF_INET
  342. socket_type = socket.SOCK_STREAM
  343. request_queue_size = 5
  344. allow_reuse_address = False
  345. allow_reuse_port = False
  346. def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
  347. """Constructor. May be extended, do not override."""
  348. BaseServer.__init__(self, server_address, RequestHandlerClass)
  349. self.socket = socket.socket(self.address_family,
  350. self.socket_type)
  351. if bind_and_activate:
  352. try:
  353. self.server_bind()
  354. self.server_activate()
  355. except:
  356. self.server_close()
  357. raise
  358. def server_bind(self):
  359. """Called by constructor to bind the socket.
  360. May be overridden.
  361. """
  362. if self.allow_reuse_address and hasattr(socket, "SO_REUSEADDR"):
  363. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  364. # Since Linux 6.12.9, SO_REUSEPORT is not allowed
  365. # on other address families than AF_INET/AF_INET6.
  366. if (
  367. self.allow_reuse_port and hasattr(socket, "SO_REUSEPORT")
  368. and self.address_family in (socket.AF_INET, socket.AF_INET6)
  369. ):
  370. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  371. self.socket.bind(self.server_address)
  372. self.server_address = self.socket.getsockname()
  373. def server_activate(self):
  374. """Called by constructor to activate the server.
  375. May be overridden.
  376. """
  377. self.socket.listen(self.request_queue_size)
  378. def server_close(self):
  379. """Called to clean-up the server.
  380. May be overridden.
  381. """
  382. self.socket.close()
  383. def fileno(self):
  384. """Return socket file number.
  385. Interface required by selector.
  386. """
  387. return self.socket.fileno()
  388. def get_request(self):
  389. """Get the request and client address from the socket.
  390. May be overridden.
  391. """
  392. return self.socket.accept()
  393. def shutdown_request(self, request):
  394. """Called to shutdown and close an individual request."""
  395. try:
  396. #explicitly shutdown. socket.close() merely releases
  397. #the socket and waits for GC to perform the actual close.
  398. request.shutdown(socket.SHUT_WR)
  399. except OSError:
  400. pass #some platforms may raise ENOTCONN here
  401. self.close_request(request)
  402. def close_request(self, request):
  403. """Called to clean up an individual request."""
  404. request.close()
  405. class UDPServer(TCPServer):
  406. """UDP server class."""
  407. allow_reuse_address = False
  408. allow_reuse_port = False
  409. socket_type = socket.SOCK_DGRAM
  410. max_packet_size = 8192
  411. def get_request(self):
  412. data, client_addr = self.socket.recvfrom(self.max_packet_size)
  413. return (data, self.socket), client_addr
  414. def server_activate(self):
  415. # No need to call listen() for UDP.
  416. pass
  417. def shutdown_request(self, request):
  418. # No need to shutdown anything.
  419. self.close_request(request)
  420. def close_request(self, request):
  421. # No need to close anything.
  422. pass
  423. if hasattr(os, "fork"):
  424. class ForkingMixIn:
  425. """Mix-in class to handle each request in a new process."""
  426. timeout = 300
  427. active_children = None
  428. max_children = 40
  429. # If true, server_close() waits until all child processes complete.
  430. block_on_close = True
  431. def collect_children(self, *, blocking=False):
  432. """Internal routine to wait for children that have exited."""
  433. if self.active_children is None:
  434. return
  435. # If we're above the max number of children, wait and reap them until
  436. # we go back below threshold. Note that we use waitpid(-1) below to be
  437. # able to collect children in size(<defunct children>) syscalls instead
  438. # of size(<children>): the downside is that this might reap children
  439. # which we didn't spawn, which is why we only resort to this when we're
  440. # above max_children.
  441. while len(self.active_children) >= self.max_children:
  442. try:
  443. pid, _ = os.waitpid(-1, 0)
  444. self.active_children.discard(pid)
  445. except ChildProcessError:
  446. # we don't have any children, we're done
  447. self.active_children.clear()
  448. except OSError:
  449. break
  450. # Now reap all defunct children.
  451. for pid in self.active_children.copy():
  452. try:
  453. flags = 0 if blocking else os.WNOHANG
  454. pid, _ = os.waitpid(pid, flags)
  455. # if the child hasn't exited yet, pid will be 0 and ignored by
  456. # discard() below
  457. self.active_children.discard(pid)
  458. except ChildProcessError:
  459. # someone else reaped it
  460. self.active_children.discard(pid)
  461. except OSError:
  462. pass
  463. def handle_timeout(self):
  464. """Wait for zombies after self.timeout seconds of inactivity.
  465. May be extended, do not override.
  466. """
  467. self.collect_children()
  468. def service_actions(self):
  469. """Collect the zombie child processes regularly in the ForkingMixIn.
  470. service_actions is called in the BaseServer's serve_forever loop.
  471. """
  472. self.collect_children()
  473. def process_request(self, request, client_address):
  474. """Fork a new subprocess to process the request."""
  475. pid = os.fork()
  476. if pid:
  477. # Parent process
  478. if self.active_children is None:
  479. self.active_children = set()
  480. self.active_children.add(pid)
  481. self.close_request(request)
  482. return
  483. else:
  484. # Child process.
  485. # This must never return, hence os._exit()!
  486. status = 1
  487. try:
  488. self.finish_request(request, client_address)
  489. status = 0
  490. except Exception:
  491. self.handle_error(request, client_address)
  492. finally:
  493. try:
  494. self.shutdown_request(request)
  495. finally:
  496. os._exit(status)
  497. def server_close(self):
  498. super().server_close()
  499. self.collect_children(blocking=self.block_on_close)
  500. class _Threads(list):
  501. """
  502. Joinable list of all non-daemon threads.
  503. """
  504. def append(self, thread):
  505. self.reap()
  506. if thread.daemon:
  507. return
  508. super().append(thread)
  509. def pop_all(self):
  510. self[:], result = [], self[:]
  511. return result
  512. def join(self):
  513. for thread in self.pop_all():
  514. thread.join()
  515. def reap(self):
  516. self[:] = (thread for thread in self if thread.is_alive())
  517. class _NoThreads:
  518. """
  519. Degenerate version of _Threads.
  520. """
  521. def append(self, thread):
  522. pass
  523. def join(self):
  524. pass
  525. class ThreadingMixIn:
  526. """Mix-in class to handle each request in a new thread."""
  527. # Decides how threads will act upon termination of the
  528. # main process
  529. daemon_threads = False
  530. # If true, server_close() waits until all non-daemonic threads terminate.
  531. block_on_close = True
  532. # Threads object
  533. # used by server_close() to wait for all threads completion.
  534. _threads = _NoThreads()
  535. def process_request_thread(self, request, client_address):
  536. """Same as in BaseServer but as a thread.
  537. In addition, exception handling is done here.
  538. """
  539. try:
  540. self.finish_request(request, client_address)
  541. except Exception:
  542. self.handle_error(request, client_address)
  543. finally:
  544. self.shutdown_request(request)
  545. def process_request(self, request, client_address):
  546. """Start a new thread to process the request."""
  547. if self.block_on_close:
  548. vars(self).setdefault('_threads', _Threads())
  549. t = threading.Thread(target = self.process_request_thread,
  550. args = (request, client_address))
  551. t.daemon = self.daemon_threads
  552. self._threads.append(t)
  553. t.start()
  554. def server_close(self):
  555. super().server_close()
  556. self._threads.join()
  557. if hasattr(os, "fork"):
  558. class ForkingUDPServer(ForkingMixIn, UDPServer): pass
  559. class ForkingTCPServer(ForkingMixIn, TCPServer): pass
  560. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  561. class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
  562. if hasattr(socket, 'AF_UNIX'):
  563. class UnixStreamServer(TCPServer):
  564. address_family = socket.AF_UNIX
  565. class UnixDatagramServer(UDPServer):
  566. address_family = socket.AF_UNIX
  567. class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
  568. class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
  569. if hasattr(os, "fork"):
  570. class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass
  571. class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass
  572. class BaseRequestHandler:
  573. """Base class for request handler classes.
  574. This class is instantiated for each request to be handled. The
  575. constructor sets the instance variables request, client_address
  576. and server, and then calls the handle() method. To implement a
  577. specific service, all you need to do is to derive a class which
  578. defines a handle() method.
  579. The handle() method can find the request as self.request, the
  580. client address as self.client_address, and the server (in case it
  581. needs access to per-server information) as self.server. Since a
  582. separate instance is created for each request, the handle() method
  583. can define other arbitrary instance variables.
  584. """
  585. def __init__(self, request, client_address, server):
  586. self.request = request
  587. self.client_address = client_address
  588. self.server = server
  589. self.setup()
  590. try:
  591. self.handle()
  592. finally:
  593. self.finish()
  594. def setup(self):
  595. pass
  596. def handle(self):
  597. pass
  598. def finish(self):
  599. pass
  600. # The following two classes make it possible to use the same service
  601. # class for stream or datagram servers.
  602. # Each class sets up these instance variables:
  603. # - rfile: a file object from which receives the request is read
  604. # - wfile: a file object to which the reply is written
  605. # When the handle() method returns, wfile is flushed properly
  606. class StreamRequestHandler(BaseRequestHandler):
  607. """Define self.rfile and self.wfile for stream sockets."""
  608. # Default buffer sizes for rfile, wfile.
  609. # We default rfile to buffered because otherwise it could be
  610. # really slow for large data (a getc() call per byte); we make
  611. # wfile unbuffered because (a) often after a write() we want to
  612. # read and we need to flush the line; (b) big writes to unbuffered
  613. # files are typically optimized by stdio even when big reads
  614. # aren't.
  615. rbufsize = -1
  616. wbufsize = 0
  617. # A timeout to apply to the request socket, if not None.
  618. timeout = None
  619. # Disable nagle algorithm for this socket, if True.
  620. # Use only when wbufsize != 0, to avoid small packets.
  621. disable_nagle_algorithm = False
  622. def setup(self):
  623. self.connection = self.request
  624. if self.timeout is not None:
  625. self.connection.settimeout(self.timeout)
  626. if self.disable_nagle_algorithm:
  627. self.connection.setsockopt(socket.IPPROTO_TCP,
  628. socket.TCP_NODELAY, True)
  629. self.rfile = self.connection.makefile('rb', self.rbufsize)
  630. if self.wbufsize == 0:
  631. self.wfile = _SocketWriter(self.connection)
  632. else:
  633. self.wfile = self.connection.makefile('wb', self.wbufsize)
  634. def finish(self):
  635. if not self.wfile.closed:
  636. try:
  637. self.wfile.flush()
  638. except socket.error:
  639. # A final socket error may have occurred here, such as
  640. # the local error ECONNABORTED.
  641. pass
  642. self.wfile.close()
  643. self.rfile.close()
  644. class _SocketWriter(BufferedIOBase):
  645. """Simple writable BufferedIOBase implementation for a socket
  646. Does not hold data in a buffer, avoiding any need to call flush()."""
  647. def __init__(self, sock):
  648. self._sock = sock
  649. def writable(self):
  650. return True
  651. def write(self, b):
  652. self._sock.sendall(b)
  653. with memoryview(b) as view:
  654. return view.nbytes
  655. def fileno(self):
  656. return self._sock.fileno()
  657. class DatagramRequestHandler(BaseRequestHandler):
  658. """Define self.rfile and self.wfile for datagram sockets."""
  659. def setup(self):
  660. from io import BytesIO
  661. self.packet, self.socket = self.request
  662. self.rfile = BytesIO(self.packet)
  663. self.wfile = BytesIO()
  664. def finish(self):
  665. self.socket.sendto(self.wfile.getvalue(), self.client_address)