socketserver.py 27 KB

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