socketserver.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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. if self.allow_reuse_port and hasattr(socket, "SO_REUSEPORT"):
  365. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  366. self.socket.bind(self.server_address)
  367. self.server_address = self.socket.getsockname()
  368. def server_activate(self):
  369. """Called by constructor to activate the server.
  370. May be overridden.
  371. """
  372. self.socket.listen(self.request_queue_size)
  373. def server_close(self):
  374. """Called to clean-up the server.
  375. May be overridden.
  376. """
  377. self.socket.close()
  378. def fileno(self):
  379. """Return socket file number.
  380. Interface required by selector.
  381. """
  382. return self.socket.fileno()
  383. def get_request(self):
  384. """Get the request and client address from the socket.
  385. May be overridden.
  386. """
  387. return self.socket.accept()
  388. def shutdown_request(self, request):
  389. """Called to shutdown and close an individual request."""
  390. try:
  391. #explicitly shutdown. socket.close() merely releases
  392. #the socket and waits for GC to perform the actual close.
  393. request.shutdown(socket.SHUT_WR)
  394. except OSError:
  395. pass #some platforms may raise ENOTCONN here
  396. self.close_request(request)
  397. def close_request(self, request):
  398. """Called to clean up an individual request."""
  399. request.close()
  400. class UDPServer(TCPServer):
  401. """UDP server class."""
  402. allow_reuse_address = False
  403. allow_reuse_port = False
  404. socket_type = socket.SOCK_DGRAM
  405. max_packet_size = 8192
  406. def get_request(self):
  407. data, client_addr = self.socket.recvfrom(self.max_packet_size)
  408. return (data, self.socket), client_addr
  409. def server_activate(self):
  410. # No need to call listen() for UDP.
  411. pass
  412. def shutdown_request(self, request):
  413. # No need to shutdown anything.
  414. self.close_request(request)
  415. def close_request(self, request):
  416. # No need to close anything.
  417. pass
  418. if hasattr(os, "fork"):
  419. class ForkingMixIn:
  420. """Mix-in class to handle each request in a new process."""
  421. timeout = 300
  422. active_children = None
  423. max_children = 40
  424. # If true, server_close() waits until all child processes complete.
  425. block_on_close = True
  426. def collect_children(self, *, blocking=False):
  427. """Internal routine to wait for children that have exited."""
  428. if self.active_children is None:
  429. return
  430. # If we're above the max number of children, wait and reap them until
  431. # we go back below threshold. Note that we use waitpid(-1) below to be
  432. # able to collect children in size(<defunct children>) syscalls instead
  433. # of size(<children>): the downside is that this might reap children
  434. # which we didn't spawn, which is why we only resort to this when we're
  435. # above max_children.
  436. while len(self.active_children) >= self.max_children:
  437. try:
  438. pid, _ = os.waitpid(-1, 0)
  439. self.active_children.discard(pid)
  440. except ChildProcessError:
  441. # we don't have any children, we're done
  442. self.active_children.clear()
  443. except OSError:
  444. break
  445. # Now reap all defunct children.
  446. for pid in self.active_children.copy():
  447. try:
  448. flags = 0 if blocking else os.WNOHANG
  449. pid, _ = os.waitpid(pid, flags)
  450. # if the child hasn't exited yet, pid will be 0 and ignored by
  451. # discard() below
  452. self.active_children.discard(pid)
  453. except ChildProcessError:
  454. # someone else reaped it
  455. self.active_children.discard(pid)
  456. except OSError:
  457. pass
  458. def handle_timeout(self):
  459. """Wait for zombies after self.timeout seconds of inactivity.
  460. May be extended, do not override.
  461. """
  462. self.collect_children()
  463. def service_actions(self):
  464. """Collect the zombie child processes regularly in the ForkingMixIn.
  465. service_actions is called in the BaseServer's serve_forever loop.
  466. """
  467. self.collect_children()
  468. def process_request(self, request, client_address):
  469. """Fork a new subprocess to process the request."""
  470. pid = os.fork()
  471. if pid:
  472. # Parent process
  473. if self.active_children is None:
  474. self.active_children = set()
  475. self.active_children.add(pid)
  476. self.close_request(request)
  477. return
  478. else:
  479. # Child process.
  480. # This must never return, hence os._exit()!
  481. status = 1
  482. try:
  483. self.finish_request(request, client_address)
  484. status = 0
  485. except Exception:
  486. self.handle_error(request, client_address)
  487. finally:
  488. try:
  489. self.shutdown_request(request)
  490. finally:
  491. os._exit(status)
  492. def server_close(self):
  493. super().server_close()
  494. self.collect_children(blocking=self.block_on_close)
  495. class _Threads(list):
  496. """
  497. Joinable list of all non-daemon threads.
  498. """
  499. def append(self, thread):
  500. self.reap()
  501. if thread.daemon:
  502. return
  503. super().append(thread)
  504. def pop_all(self):
  505. self[:], result = [], self[:]
  506. return result
  507. def join(self):
  508. for thread in self.pop_all():
  509. thread.join()
  510. def reap(self):
  511. self[:] = (thread for thread in self if thread.is_alive())
  512. class _NoThreads:
  513. """
  514. Degenerate version of _Threads.
  515. """
  516. def append(self, thread):
  517. pass
  518. def join(self):
  519. pass
  520. class ThreadingMixIn:
  521. """Mix-in class to handle each request in a new thread."""
  522. # Decides how threads will act upon termination of the
  523. # main process
  524. daemon_threads = False
  525. # If true, server_close() waits until all non-daemonic threads terminate.
  526. block_on_close = True
  527. # Threads object
  528. # used by server_close() to wait for all threads completion.
  529. _threads = _NoThreads()
  530. def process_request_thread(self, request, client_address):
  531. """Same as in BaseServer but as a thread.
  532. In addition, exception handling is done here.
  533. """
  534. try:
  535. self.finish_request(request, client_address)
  536. except Exception:
  537. self.handle_error(request, client_address)
  538. finally:
  539. self.shutdown_request(request)
  540. def process_request(self, request, client_address):
  541. """Start a new thread to process the request."""
  542. if self.block_on_close:
  543. vars(self).setdefault('_threads', _Threads())
  544. t = threading.Thread(target = self.process_request_thread,
  545. args = (request, client_address))
  546. t.daemon = self.daemon_threads
  547. self._threads.append(t)
  548. t.start()
  549. def server_close(self):
  550. super().server_close()
  551. self._threads.join()
  552. if hasattr(os, "fork"):
  553. class ForkingUDPServer(ForkingMixIn, UDPServer): pass
  554. class ForkingTCPServer(ForkingMixIn, TCPServer): pass
  555. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  556. class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
  557. if hasattr(socket, 'AF_UNIX'):
  558. class UnixStreamServer(TCPServer):
  559. address_family = socket.AF_UNIX
  560. class UnixDatagramServer(UDPServer):
  561. address_family = socket.AF_UNIX
  562. class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
  563. class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
  564. if hasattr(os, "fork"):
  565. class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass
  566. class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass
  567. class BaseRequestHandler:
  568. """Base class for request handler classes.
  569. This class is instantiated for each request to be handled. The
  570. constructor sets the instance variables request, client_address
  571. and server, and then calls the handle() method. To implement a
  572. specific service, all you need to do is to derive a class which
  573. defines a handle() method.
  574. The handle() method can find the request as self.request, the
  575. client address as self.client_address, and the server (in case it
  576. needs access to per-server information) as self.server. Since a
  577. separate instance is created for each request, the handle() method
  578. can define other arbitrary instance variables.
  579. """
  580. def __init__(self, request, client_address, server):
  581. self.request = request
  582. self.client_address = client_address
  583. self.server = server
  584. self.setup()
  585. try:
  586. self.handle()
  587. finally:
  588. self.finish()
  589. def setup(self):
  590. pass
  591. def handle(self):
  592. pass
  593. def finish(self):
  594. pass
  595. # The following two classes make it possible to use the same service
  596. # class for stream or datagram servers.
  597. # Each class sets up these instance variables:
  598. # - rfile: a file object from which receives the request is read
  599. # - wfile: a file object to which the reply is written
  600. # When the handle() method returns, wfile is flushed properly
  601. class StreamRequestHandler(BaseRequestHandler):
  602. """Define self.rfile and self.wfile for stream sockets."""
  603. # Default buffer sizes for rfile, wfile.
  604. # We default rfile to buffered because otherwise it could be
  605. # really slow for large data (a getc() call per byte); we make
  606. # wfile unbuffered because (a) often after a write() we want to
  607. # read and we need to flush the line; (b) big writes to unbuffered
  608. # files are typically optimized by stdio even when big reads
  609. # aren't.
  610. rbufsize = -1
  611. wbufsize = 0
  612. # A timeout to apply to the request socket, if not None.
  613. timeout = None
  614. # Disable nagle algorithm for this socket, if True.
  615. # Use only when wbufsize != 0, to avoid small packets.
  616. disable_nagle_algorithm = False
  617. def setup(self):
  618. self.connection = self.request
  619. if self.timeout is not None:
  620. self.connection.settimeout(self.timeout)
  621. if self.disable_nagle_algorithm:
  622. self.connection.setsockopt(socket.IPPROTO_TCP,
  623. socket.TCP_NODELAY, True)
  624. self.rfile = self.connection.makefile('rb', self.rbufsize)
  625. if self.wbufsize == 0:
  626. self.wfile = _SocketWriter(self.connection)
  627. else:
  628. self.wfile = self.connection.makefile('wb', self.wbufsize)
  629. def finish(self):
  630. if not self.wfile.closed:
  631. try:
  632. self.wfile.flush()
  633. except socket.error:
  634. # A final socket error may have occurred here, such as
  635. # the local error ECONNABORTED.
  636. pass
  637. self.wfile.close()
  638. self.rfile.close()
  639. class _SocketWriter(BufferedIOBase):
  640. """Simple writable BufferedIOBase implementation for a socket
  641. Does not hold data in a buffer, avoiding any need to call flush()."""
  642. def __init__(self, sock):
  643. self._sock = sock
  644. def writable(self):
  645. return True
  646. def write(self, b):
  647. self._sock.sendall(b)
  648. with memoryview(b) as view:
  649. return view.nbytes
  650. def fileno(self):
  651. return self._sock.fileno()
  652. class DatagramRequestHandler(BaseRequestHandler):
  653. """Define self.rfile and self.wfile for datagram sockets."""
  654. def setup(self):
  655. from io import BytesIO
  656. self.packet, self.socket = self.request
  657. self.rfile = BytesIO(self.packet)
  658. self.wfile = BytesIO()
  659. def finish(self):
  660. self.socket.sendto(self.wfile.getvalue(), self.client_address)