socketserver.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. # poll/select have the advantage of not requiring any extra file descriptor,
  116. # contrarily to epoll/kqueue (also, they require a single syscall).
  117. if hasattr(selectors, 'PollSelector'):
  118. _ServerSelector = selectors.PollSelector
  119. else:
  120. _ServerSelector = selectors.SelectSelector
  121. class BaseServer:
  122. """Base class for server classes.
  123. Methods for the caller:
  124. - __init__(server_address, RequestHandlerClass)
  125. - serve_forever(poll_interval=0.5)
  126. - shutdown()
  127. - handle_request() # if you do not use serve_forever()
  128. - fileno() -> int # for selector
  129. Methods that may be overridden:
  130. - server_bind()
  131. - server_activate()
  132. - get_request() -> request, client_address
  133. - handle_timeout()
  134. - verify_request(request, client_address)
  135. - server_close()
  136. - process_request(request, client_address)
  137. - shutdown_request(request)
  138. - close_request(request)
  139. - service_actions()
  140. - handle_error()
  141. Methods for derived classes:
  142. - finish_request(request, client_address)
  143. Class variables that may be overridden by derived classes or
  144. instances:
  145. - timeout
  146. - address_family
  147. - socket_type
  148. - allow_reuse_address
  149. Instance variables:
  150. - RequestHandlerClass
  151. - socket
  152. """
  153. timeout = None
  154. def __init__(self, server_address, RequestHandlerClass):
  155. """Constructor. May be extended, do not override."""
  156. self.server_address = server_address
  157. self.RequestHandlerClass = RequestHandlerClass
  158. self.__is_shut_down = threading.Event()
  159. self.__shutdown_request = False
  160. def server_activate(self):
  161. """Called by constructor to activate the server.
  162. May be overridden.
  163. """
  164. pass
  165. def serve_forever(self, poll_interval=0.5):
  166. """Handle one request at a time until shutdown.
  167. Polls for shutdown every poll_interval seconds. Ignores
  168. self.timeout. If you need to do periodic tasks, do them in
  169. another thread.
  170. """
  171. self.__is_shut_down.clear()
  172. try:
  173. # XXX: Consider using another file descriptor or connecting to the
  174. # socket to wake this up instead of polling. Polling reduces our
  175. # responsiveness to a shutdown request and wastes cpu at all other
  176. # times.
  177. with _ServerSelector() as selector:
  178. selector.register(self, selectors.EVENT_READ)
  179. while not self.__shutdown_request:
  180. ready = selector.select(poll_interval)
  181. # bpo-35017: shutdown() called during select(), exit immediately.
  182. if self.__shutdown_request:
  183. break
  184. if ready:
  185. self._handle_request_noblock()
  186. self.service_actions()
  187. finally:
  188. self.__shutdown_request = False
  189. self.__is_shut_down.set()
  190. def shutdown(self):
  191. """Stops the serve_forever loop.
  192. Blocks until the loop has finished. This must be called while
  193. serve_forever() is running in another thread, or it will
  194. deadlock.
  195. """
  196. self.__shutdown_request = True
  197. self.__is_shut_down.wait()
  198. def service_actions(self):
  199. """Called by the serve_forever() loop.
  200. May be overridden by a subclass / Mixin to implement any code that
  201. needs to be run during the loop.
  202. """
  203. pass
  204. # The distinction between handling, getting, processing and finishing a
  205. # request is fairly arbitrary. Remember:
  206. #
  207. # - handle_request() is the top-level call. It calls selector.select(),
  208. # get_request(), verify_request() and process_request()
  209. # - get_request() is different for stream or datagram sockets
  210. # - process_request() is the place that may fork a new process or create a
  211. # new thread to finish the request
  212. # - finish_request() instantiates the request handler class; this
  213. # constructor will handle the request all by itself
  214. def handle_request(self):
  215. """Handle one request, possibly blocking.
  216. Respects self.timeout.
  217. """
  218. # Support people who used socket.settimeout() to escape
  219. # handle_request before self.timeout was available.
  220. timeout = self.socket.gettimeout()
  221. if timeout is None:
  222. timeout = self.timeout
  223. elif self.timeout is not None:
  224. timeout = min(timeout, self.timeout)
  225. if timeout is not None:
  226. deadline = time() + timeout
  227. # Wait until a request arrives or the timeout expires - the loop is
  228. # necessary to accommodate early wakeups due to EINTR.
  229. with _ServerSelector() as selector:
  230. selector.register(self, selectors.EVENT_READ)
  231. while True:
  232. ready = selector.select(timeout)
  233. if ready:
  234. return self._handle_request_noblock()
  235. else:
  236. if timeout is not None:
  237. timeout = deadline - time()
  238. if timeout < 0:
  239. return self.handle_timeout()
  240. def _handle_request_noblock(self):
  241. """Handle one request, without blocking.
  242. I assume that selector.select() has returned that the socket is
  243. readable before this function was called, so there should be no risk of
  244. blocking in get_request().
  245. """
  246. try:
  247. request, client_address = self.get_request()
  248. except OSError:
  249. return
  250. if self.verify_request(request, client_address):
  251. try:
  252. self.process_request(request, client_address)
  253. except Exception:
  254. self.handle_error(request, client_address)
  255. self.shutdown_request(request)
  256. except:
  257. self.shutdown_request(request)
  258. raise
  259. else:
  260. self.shutdown_request(request)
  261. def handle_timeout(self):
  262. """Called if no new request arrives within self.timeout.
  263. Overridden by ForkingMixIn.
  264. """
  265. pass
  266. def verify_request(self, request, client_address):
  267. """Verify the request. May be overridden.
  268. Return True if we should proceed with this request.
  269. """
  270. return True
  271. def process_request(self, request, client_address):
  272. """Call finish_request.
  273. Overridden by ForkingMixIn and ThreadingMixIn.
  274. """
  275. self.finish_request(request, client_address)
  276. self.shutdown_request(request)
  277. def server_close(self):
  278. """Called to clean-up the server.
  279. May be overridden.
  280. """
  281. pass
  282. def finish_request(self, request, client_address):
  283. """Finish one request by instantiating RequestHandlerClass."""
  284. self.RequestHandlerClass(request, client_address, self)
  285. def shutdown_request(self, request):
  286. """Called to shutdown and close an individual request."""
  287. self.close_request(request)
  288. def close_request(self, request):
  289. """Called to clean up an individual request."""
  290. pass
  291. def handle_error(self, request, client_address):
  292. """Handle an error gracefully. May be overridden.
  293. The default is to print a traceback and continue.
  294. """
  295. print('-'*40, file=sys.stderr)
  296. print('Exception occurred during processing of request from',
  297. client_address, file=sys.stderr)
  298. import traceback
  299. traceback.print_exc()
  300. print('-'*40, file=sys.stderr)
  301. def __enter__(self):
  302. return self
  303. def __exit__(self, *args):
  304. self.server_close()
  305. class TCPServer(BaseServer):
  306. """Base class for various socket-based server classes.
  307. Defaults to synchronous IP stream (i.e., TCP).
  308. Methods for the caller:
  309. - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
  310. - serve_forever(poll_interval=0.5)
  311. - shutdown()
  312. - handle_request() # if you don't use serve_forever()
  313. - fileno() -> int # for selector
  314. Methods that may be overridden:
  315. - server_bind()
  316. - server_activate()
  317. - get_request() -> request, client_address
  318. - handle_timeout()
  319. - verify_request(request, client_address)
  320. - process_request(request, client_address)
  321. - shutdown_request(request)
  322. - close_request(request)
  323. - handle_error()
  324. Methods for derived classes:
  325. - finish_request(request, client_address)
  326. Class variables that may be overridden by derived classes or
  327. instances:
  328. - timeout
  329. - address_family
  330. - socket_type
  331. - request_queue_size (only for stream sockets)
  332. - allow_reuse_address
  333. Instance variables:
  334. - server_address
  335. - RequestHandlerClass
  336. - socket
  337. """
  338. address_family = socket.AF_INET
  339. socket_type = socket.SOCK_STREAM
  340. request_queue_size = 5
  341. allow_reuse_address = False
  342. def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
  343. """Constructor. May be extended, do not override."""
  344. BaseServer.__init__(self, server_address, RequestHandlerClass)
  345. self.socket = socket.socket(self.address_family,
  346. self.socket_type)
  347. if bind_and_activate:
  348. try:
  349. self.server_bind()
  350. self.server_activate()
  351. except:
  352. self.server_close()
  353. raise
  354. def server_bind(self):
  355. """Called by constructor to bind the socket.
  356. May be overridden.
  357. """
  358. if self.allow_reuse_address:
  359. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  360. self.socket.bind(self.server_address)
  361. self.server_address = self.socket.getsockname()
  362. def server_activate(self):
  363. """Called by constructor to activate the server.
  364. May be overridden.
  365. """
  366. self.socket.listen(self.request_queue_size)
  367. def server_close(self):
  368. """Called to clean-up the server.
  369. May be overridden.
  370. """
  371. self.socket.close()
  372. def fileno(self):
  373. """Return socket file number.
  374. Interface required by selector.
  375. """
  376. return self.socket.fileno()
  377. def get_request(self):
  378. """Get the request and client address from the socket.
  379. May be overridden.
  380. """
  381. return self.socket.accept()
  382. def shutdown_request(self, request):
  383. """Called to shutdown and close an individual request."""
  384. try:
  385. #explicitly shutdown. socket.close() merely releases
  386. #the socket and waits for GC to perform the actual close.
  387. request.shutdown(socket.SHUT_WR)
  388. except OSError:
  389. pass #some platforms may raise ENOTCONN here
  390. self.close_request(request)
  391. def close_request(self, request):
  392. """Called to clean up an individual request."""
  393. request.close()
  394. class UDPServer(TCPServer):
  395. """UDP server class."""
  396. allow_reuse_address = False
  397. socket_type = socket.SOCK_DGRAM
  398. max_packet_size = 8192
  399. def get_request(self):
  400. data, client_addr = self.socket.recvfrom(self.max_packet_size)
  401. return (data, self.socket), client_addr
  402. def server_activate(self):
  403. # No need to call listen() for UDP.
  404. pass
  405. def shutdown_request(self, request):
  406. # No need to shutdown anything.
  407. self.close_request(request)
  408. def close_request(self, request):
  409. # No need to close anything.
  410. pass
  411. if hasattr(os, "fork"):
  412. class ForkingMixIn:
  413. """Mix-in class to handle each request in a new process."""
  414. timeout = 300
  415. active_children = None
  416. max_children = 40
  417. # If true, server_close() waits until all child processes complete.
  418. block_on_close = True
  419. def collect_children(self, *, blocking=False):
  420. """Internal routine to wait for children that have exited."""
  421. if self.active_children is None:
  422. return
  423. # If we're above the max number of children, wait and reap them until
  424. # we go back below threshold. Note that we use waitpid(-1) below to be
  425. # able to collect children in size(<defunct children>) syscalls instead
  426. # of size(<children>): the downside is that this might reap children
  427. # which we didn't spawn, which is why we only resort to this when we're
  428. # above max_children.
  429. while len(self.active_children) >= self.max_children:
  430. try:
  431. pid, _ = os.waitpid(-1, 0)
  432. self.active_children.discard(pid)
  433. except ChildProcessError:
  434. # we don't have any children, we're done
  435. self.active_children.clear()
  436. except OSError:
  437. break
  438. # Now reap all defunct children.
  439. for pid in self.active_children.copy():
  440. try:
  441. flags = 0 if blocking else os.WNOHANG
  442. pid, _ = os.waitpid(pid, flags)
  443. # if the child hasn't exited yet, pid will be 0 and ignored by
  444. # discard() below
  445. self.active_children.discard(pid)
  446. except ChildProcessError:
  447. # someone else reaped it
  448. self.active_children.discard(pid)
  449. except OSError:
  450. pass
  451. def handle_timeout(self):
  452. """Wait for zombies after self.timeout seconds of inactivity.
  453. May be extended, do not override.
  454. """
  455. self.collect_children()
  456. def service_actions(self):
  457. """Collect the zombie child processes regularly in the ForkingMixIn.
  458. service_actions is called in the BaseServer's serve_forever loop.
  459. """
  460. self.collect_children()
  461. def process_request(self, request, client_address):
  462. """Fork a new subprocess to process the request."""
  463. pid = os.fork()
  464. if pid:
  465. # Parent process
  466. if self.active_children is None:
  467. self.active_children = set()
  468. self.active_children.add(pid)
  469. self.close_request(request)
  470. return
  471. else:
  472. # Child process.
  473. # This must never return, hence os._exit()!
  474. status = 1
  475. try:
  476. self.finish_request(request, client_address)
  477. status = 0
  478. except Exception:
  479. self.handle_error(request, client_address)
  480. finally:
  481. try:
  482. self.shutdown_request(request)
  483. finally:
  484. os._exit(status)
  485. def server_close(self):
  486. super().server_close()
  487. self.collect_children(blocking=self.block_on_close)
  488. class _Threads(list):
  489. """
  490. Joinable list of all non-daemon threads.
  491. """
  492. def append(self, thread):
  493. self.reap()
  494. if thread.daemon:
  495. return
  496. super().append(thread)
  497. def pop_all(self):
  498. self[:], result = [], self[:]
  499. return result
  500. def join(self):
  501. for thread in self.pop_all():
  502. thread.join()
  503. def reap(self):
  504. self[:] = (thread for thread in self if thread.is_alive())
  505. class _NoThreads:
  506. """
  507. Degenerate version of _Threads.
  508. """
  509. def append(self, thread):
  510. pass
  511. def join(self):
  512. pass
  513. class ThreadingMixIn:
  514. """Mix-in class to handle each request in a new thread."""
  515. # Decides how threads will act upon termination of the
  516. # main process
  517. daemon_threads = False
  518. # If true, server_close() waits until all non-daemonic threads terminate.
  519. block_on_close = True
  520. # Threads object
  521. # used by server_close() to wait for all threads completion.
  522. _threads = _NoThreads()
  523. def process_request_thread(self, request, client_address):
  524. """Same as in BaseServer but as a thread.
  525. In addition, exception handling is done here.
  526. """
  527. try:
  528. self.finish_request(request, client_address)
  529. except Exception:
  530. self.handle_error(request, client_address)
  531. finally:
  532. self.shutdown_request(request)
  533. def process_request(self, request, client_address):
  534. """Start a new thread to process the request."""
  535. if self.block_on_close:
  536. vars(self).setdefault('_threads', _Threads())
  537. t = threading.Thread(target = self.process_request_thread,
  538. args = (request, client_address))
  539. t.daemon = self.daemon_threads
  540. self._threads.append(t)
  541. t.start()
  542. def server_close(self):
  543. super().server_close()
  544. self._threads.join()
  545. if hasattr(os, "fork"):
  546. class ForkingUDPServer(ForkingMixIn, UDPServer): pass
  547. class ForkingTCPServer(ForkingMixIn, TCPServer): pass
  548. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  549. class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
  550. if hasattr(socket, 'AF_UNIX'):
  551. class UnixStreamServer(TCPServer):
  552. address_family = socket.AF_UNIX
  553. class UnixDatagramServer(UDPServer):
  554. address_family = socket.AF_UNIX
  555. class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
  556. class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
  557. class BaseRequestHandler:
  558. """Base class for request handler classes.
  559. This class is instantiated for each request to be handled. The
  560. constructor sets the instance variables request, client_address
  561. and server, and then calls the handle() method. To implement a
  562. specific service, all you need to do is to derive a class which
  563. defines a handle() method.
  564. The handle() method can find the request as self.request, the
  565. client address as self.client_address, and the server (in case it
  566. needs access to per-server information) as self.server. Since a
  567. separate instance is created for each request, the handle() method
  568. can define other arbitrary instance variables.
  569. """
  570. def __init__(self, request, client_address, server):
  571. self.request = request
  572. self.client_address = client_address
  573. self.server = server
  574. self.setup()
  575. try:
  576. self.handle()
  577. finally:
  578. self.finish()
  579. def setup(self):
  580. pass
  581. def handle(self):
  582. pass
  583. def finish(self):
  584. pass
  585. # The following two classes make it possible to use the same service
  586. # class for stream or datagram servers.
  587. # Each class sets up these instance variables:
  588. # - rfile: a file object from which receives the request is read
  589. # - wfile: a file object to which the reply is written
  590. # When the handle() method returns, wfile is flushed properly
  591. class StreamRequestHandler(BaseRequestHandler):
  592. """Define self.rfile and self.wfile for stream sockets."""
  593. # Default buffer sizes for rfile, wfile.
  594. # We default rfile to buffered because otherwise it could be
  595. # really slow for large data (a getc() call per byte); we make
  596. # wfile unbuffered because (a) often after a write() we want to
  597. # read and we need to flush the line; (b) big writes to unbuffered
  598. # files are typically optimized by stdio even when big reads
  599. # aren't.
  600. rbufsize = -1
  601. wbufsize = 0
  602. # A timeout to apply to the request socket, if not None.
  603. timeout = None
  604. # Disable nagle algorithm for this socket, if True.
  605. # Use only when wbufsize != 0, to avoid small packets.
  606. disable_nagle_algorithm = False
  607. def setup(self):
  608. self.connection = self.request
  609. if self.timeout is not None:
  610. self.connection.settimeout(self.timeout)
  611. if self.disable_nagle_algorithm:
  612. self.connection.setsockopt(socket.IPPROTO_TCP,
  613. socket.TCP_NODELAY, True)
  614. self.rfile = self.connection.makefile('rb', self.rbufsize)
  615. if self.wbufsize == 0:
  616. self.wfile = _SocketWriter(self.connection)
  617. else:
  618. self.wfile = self.connection.makefile('wb', self.wbufsize)
  619. def finish(self):
  620. if not self.wfile.closed:
  621. try:
  622. self.wfile.flush()
  623. except socket.error:
  624. # A final socket error may have occurred here, such as
  625. # the local error ECONNABORTED.
  626. pass
  627. self.wfile.close()
  628. self.rfile.close()
  629. class _SocketWriter(BufferedIOBase):
  630. """Simple writable BufferedIOBase implementation for a socket
  631. Does not hold data in a buffer, avoiding any need to call flush()."""
  632. def __init__(self, sock):
  633. self._sock = sock
  634. def writable(self):
  635. return True
  636. def write(self, b):
  637. self._sock.sendall(b)
  638. with memoryview(b) as view:
  639. return view.nbytes
  640. def fileno(self):
  641. return self._sock.fileno()
  642. class DatagramRequestHandler(BaseRequestHandler):
  643. """Define self.rfile and self.wfile for datagram sockets."""
  644. def setup(self):
  645. from io import BytesIO
  646. self.packet, self.socket = self.request
  647. self.rfile = BytesIO(self.packet)
  648. self.wfile = BytesIO()
  649. def finish(self):
  650. self.socket.sendto(self.wfile.getvalue(), self.client_address)