3 \i@sdZdZddlZddlZddlZddlZddlZy ddlZWnek rXddl ZYnXddl m Z ddl m Z dddd d d d d dg ZeedrejdddgeedrejddddgeedrejZnejZGdddZGdddeZGdddeZeedrGdddZGdddZeedr\GdddeeZGdddeeZGd d d eeZGd!d d eeZeedrGd"ddeZGd#ddeZGd$ddeeZGd%ddeeZ Gd&d d Z!Gd'd d e!Z"Gd(d)d)e Z#Gd*d d e!Z$dS)+apGeneric socket server classes. This module tries to capture the various aspects of defining a server: For socket-based servers: - address family: - AF_INET{,6}: IP (Internet Protocol) sockets (default) - AF_UNIX: Unix domain sockets - others, e.g. AF_DECNET are conceivable (see - socket type: - SOCK_STREAM (reliable stream, e.g. TCP) - SOCK_DGRAM (datagrams, e.g. UDP) For request-based servers (including socket-based): - client address verification before further looking at the request (This is actually a hook for any processing that needs to look at the request before anything else, e.g. logging) - how to handle multiple requests: - synchronous (one request is handled at a time) - forking (each request is handled by a new process) - threading (each request is handled by a new thread) The classes in this module favor the server type that is simplest to write: a synchronous TCP/IP server. This is bad class design, but save some typing. (There's also the issue that a deep class hierarchy slows down method lookups.) There are five classes in an inheritance diagram, four of which represent synchronous servers of four types: +------------+ | BaseServer | +------------+ | v +-----------+ +------------------+ | TCPServer |------->| UnixStreamServer | +-----------+ +------------------+ | v +-----------+ +--------------------+ | UDPServer |------->| UnixDatagramServer | +-----------+ +--------------------+ Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer -- the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both unix server classes. Forking and threading versions of each type of server can be created using the ForkingMixIn and ThreadingMixIn mix-in classes. For instance, a threading UDP server class is created as follows: class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass The Mix-in class must come first, since it overrides a method defined in UDPServer! Setting the various member variables also changes the behavior of the underlying server mechanism. To implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class. The request handler class must be different for datagram or stream services. This can be hidden by using the request handler subclasses StreamRequestHandler or DatagramRequestHandler. Of course, you still have to use your head! For instance, it makes no sense to use a forking server if the service contains state in memory that can be modified by requests (since the modifications in the child process would never reach the initial state kept in the parent process and passed to each child). In this case, you can use a threading server, but you will probably have to use locks to avoid two requests that come in nearly simultaneous to apply conflicting changes to the server state. On the other hand, if you are building e.g. an HTTP server, where all data is stored externally (e.g. in the file system), a synchronous class will essentially render the service "deaf" while one request is being handled -- which may be for a very long time if a client is slow to read all the data it has requested. Here a threading or forking server is appropriate. In some cases, it may be appropriate to process part of a request synchronously, but to finish processing in a forked child depending on the request data. This can be implemented by using a synchronous server and doing an explicit fork in the request handler class handle() method. Another approach to handling multiple simultaneous requests in an environment that supports neither threads nor fork (or where these are too expensive or inappropriate for the service) is to maintain an explicit table of partially finished requests and to use a selector to decide which request to work on next (or whether to handle a new incoming request). This is particularly important for stream services where each client can potentially be connected for a long time (if threads or subprocesses cannot be used). Future work: - Standard classes for Sun RPC (which uses either UDP or TCP) - Standard mix-in classes to implement various authentication and encryption schemes XXX Open problems: - What to do with out-of-band data? BaseServer: - split generic "request" functionality out into BaseServer class. Copyright (C) 2000 Luke Kenneth Casson Leighton example: read entries from a SQL database (requires overriding get_request() to return a table entry from the database). entry is processed by a RequestHandlerClass. z0.4N)BufferedIOBase) monotonic BaseServer TCPServer UDPServerThreadingUDPServerThreadingTCPServerBaseRequestHandlerStreamRequestHandlerDatagramRequestHandlerThreadingMixInforkForkingUDPServerForkingTCPServer ForkingMixInAF_UNIXUnixStreamServerUnixDatagramServerThreadingUnixStreamServerThreadingUnixDatagramServer PollSelectorc@seZdZdZdZddZddZd&dd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZddZd d!Zd"d#Zd$d%ZdS)'raBase class for server classes. Methods for the caller: - __init__(server_address, RequestHandlerClass) - serve_forever(poll_interval=0.5) - shutdown() - handle_request() # if you do not use serve_forever() - fileno() -> int # for selector Methods that may be overridden: - server_bind() - server_activate() - get_request() -> request, client_address - handle_timeout() - verify_request(request, client_address) - server_close() - process_request(request, client_address) - shutdown_request(request) - close_request(request) - service_actions() - handle_error() Methods for derived classes: - finish_request(request, client_address) Class variables that may be overridden by derived classes or instances: - timeout - address_family - socket_type - allow_reuse_address Instance variables: - RequestHandlerClass - socket NcCs ||_||_tj|_d|_dS)z/Constructor. May be extended, do not override.FN)server_addressRequestHandlerClass threadingZEvent_BaseServer__is_shut_down_BaseServer__shutdown_request)selfrrr$/usr/lib64/python3.6/socketserver.py__init__s zBaseServer.__init__cCsdS)zSCalled by constructor to activate the server. May be overridden. Nr)rrrrserver_activateszBaseServer.server_activate?cCsx|jjzVtF}|j|tjx0|jsR|j|}|jrrrrr8QszBaseServer.verify_requestcCs|j|||j|dS)zVCall finish_request. Overridden by ForkingMixIn and ThreadingMixIn. N)finish_requestr<)rr=r>rrrr9Ys zBaseServer.process_requestcCsdS)zDCalled to clean-up the server. May be overridden. Nr)rrrr server_closebszBaseServer.server_closecCs|j|||dS)z8Finish one request by instantiating RequestHandlerClass.N)r)rr=r>rrrr?jszBaseServer.finish_requestcCs|j|dS)z3Called to shutdown and close an individual request.N) close_request)rr=rrrr<nszBaseServer.shutdown_requestcCsdS)z)Called to clean up an individual request.Nr)rr=rrrrArszBaseServer.close_requestcCsHtddtjdtd|tjdddl}|jtddtjddS)ztHandle an error gracefully. May be overridden. The default is to print a traceback and continue. -()filez4Exception happened during processing of request fromrN)printsysstderr traceback print_exc)rr=r>rHrrrr;vs  zBaseServer.handle_errorcCs|S)Nr)rrrr __enter__szBaseServer.__enter__cGs |jdS)N)r@)rargsrrr__exit__szBaseServer.__exit__)r!)__name__ __module__ __qualname____doc__r1rr r-r/r)r5r(r4r8r9r@r?r<rAr;rJrLrrrrrs&+    c@sfeZdZdZejZejZdZ dZ dddZ ddZ d d Z d d Zd dZddZddZddZdS)ra3Base class for various socket-based server classes. Defaults to synchronous IP stream (i.e., TCP). Methods for the caller: - __init__(server_address, RequestHandlerClass, bind_and_activate=True) - serve_forever(poll_interval=0.5) - shutdown() - handle_request() # if you don't use serve_forever() - fileno() -> int # for selector Methods that may be overridden: - server_bind() - server_activate() - get_request() -> request, client_address - handle_timeout() - verify_request(request, client_address) - process_request(request, client_address) - shutdown_request(request) - close_request(request) - handle_error() Methods for derived classes: - finish_request(request, client_address) Class variables that may be overridden by derived classes or instances: - timeout - address_family - socket_type - request_queue_size (only for stream sockets) - allow_reuse_address Instance variables: - server_address - RequestHandlerClass - socket FTc CsTtj|||tj|j|j|_|rPy|j|jWn|jYnXdS)z/Constructor. May be extended, do not override.N)rrr0address_family socket_type server_bindr r@)rrrZbind_and_activaterrrrs  zTCPServer.__init__cCs8|jr|jjtjtjd|jj|j|jj|_dS)zOCalled by constructor to bind the socket. May be overridden. N)allow_reuse_addressr0 setsockoptZ SOL_SOCKETZ SO_REUSEADDRZbindrZ getsockname)rrrrrTszTCPServer.server_bindcCs|jj|jdS)zSCalled by constructor to activate the server. May be overridden. N)r0Zlistenrequest_queue_size)rrrrr szTCPServer.server_activatecCs|jjdS)zDCalled to clean-up the server. May be overridden. N)r0close)rrrrr@szTCPServer.server_closecCs |jjS)zMReturn socket file number. Interface required by selector. )r0fileno)rrrrrZszTCPServer.filenocCs |jjS)zYGet the request and client address from the socket. May be overridden. )r0Zaccept)rrrrr6szTCPServer.get_requestc Cs4y|jtjWntk r$YnX|j|dS)z3Called to shutdown and close an individual request.N)r/r0ZSHUT_WRr7rA)rr=rrrr<s zTCPServer.shutdown_requestcCs |jdS)z)Called to clean up an individual request.N)rY)rr=rrrrAszTCPServer.close_requestN)T)rMrNrOrPr0ZAF_INETrRZ SOCK_STREAMrSrXrVrrTr r@rZr6r<rArrrrrs-   c@s>eZdZdZdZejZdZddZ ddZ dd Z d d Z d S) rzUDP server class.Fi cCs |jj|j\}}||jf|fS)N)r0Zrecvfrommax_packet_size)rdataZ client_addrrrrr6szUDPServer.get_requestcCsdS)Nr)rrrrr szUDPServer.server_activatecCs|j|dS)N)rA)rr=rrrr<szUDPServer.shutdown_requestcCsdS)Nr)rr=rrrrAszUDPServer.close_requestN) rMrNrOrPrVr0Z SOCK_DGRAMrSr[r6r r<rArrrrrscsVeZdZdZdZdZdZdZddddZd d Z d d Z d dZ fddZ Z S)rz5Mix-in class to handle each request in a new process.i,NrCF)blockingc Cs|jdkrdSxht|j|jkrvy tjdd\}}|jj|Wqtk r^|jjYqtk rrPYqXqWxt|jj D]f}y.|rdntj }tj||\}}|jj|Wqtk r|jj|Yqtk rYqXqWdS)z7Internal routine to wait for children that have exited.NrUr) active_childrenlen max_childrenoswaitpiddiscardChildProcessErrorr"r7copyWNOHANG)rr]pid_flagsrrrcollect_children,s&  zForkingMixIn.collect_childrencCs |jdS)zvWait for zombies after self.timeout seconds of inactivity. May be extended, do not override. N)rk)rrrrr4OszForkingMixIn.handle_timeoutcCs |jdS)zCollect the zombie child processes regularly in the ForkingMixIn. service_actions is called in the BaseServer's serve_forver loop. N)rk)rrrrr)VszForkingMixIn.service_actionscCstj}|r8|jdkrt|_|jj||j|dSd}z:y|j||d}Wn tk rr|j||YnXWdz|j |Wdtj |XXdS)z-Fork a new subprocess to process the request.NrUr) rbr r_r*addrAr?r:r;r<_exit)rr=r>rhZstatusrrrr9]s     zForkingMixIn.process_requestcstj|j|jddS)N)r])superr@rk_block_on_close)r) __class__rrr@vs zForkingMixIn.server_close)rMrNrOrPr1r_rarorkr4r)r9r@ __classcell__rr)rprr#s#cs<eZdZdZdZdZdZddZddZfdd Z Z S) r z4Mix-in class to handle each request in a new thread.FNcCsHz6y|j||Wn tk r2|j||YnXWd|j|XdS)zgSame as in BaseServer but as a thread. In addition, exception handling is done here. N)r?r:r;r<)rr=r>rrrprocess_request_threads z%ThreadingMixIn.process_request_threadcCsRtj|j||fd}|j|_|j rF|jrF|jdkr:g|_|jj||jdS)z*Start a new thread to process the request.)targetrKN) rZThreadrrdaemon_threadsZdaemonro_threadsappendstart)rr=r>trrrr9s   zThreadingMixIn.process_requestcs:tj|jr6|j}d|_|r6x|D] }|jq&WdS)N)rnr@rorujoin)rZthreadsZthread)rprrr@s  zThreadingMixIn.server_close) rMrNrOrPrtrorurrr9r@rqrr)rprr {s  c@s eZdZdS)rN)rMrNrOrrrrrsc@s eZdZdS)rN)rMrNrOrrrrrsc@s eZdZdS)rN)rMrNrOrrrrrsc@s eZdZdS)rN)rMrNrOrrrrrsc@seZdZejZdS)rN)rMrNrOr0rrRrrrrrsc@seZdZejZdS)rN)rMrNrOr0rrRrrrrrsc@s eZdZdS)rN)rMrNrOrrrrrsc@s eZdZdS)rN)rMrNrOrrrrrsc@s0eZdZdZddZddZddZdd Zd S) r aBase class for request handler classes. This class is instantiated for each request to be handled. The constructor sets the instance variables request, client_address and server, and then calls the handle() method. To implement a specific service, all you need to do is to derive a class which defines a handle() method. The handle() method can find the request as self.request, the client address as self.client_address, and the server (in case it needs access to per-server information) as self.server. Since a separate instance is created for each request, the handle() method can define other arbitrary instance variables. c Cs6||_||_||_|jz |jWd|jXdS)N)r=r>serversetuphandlefinish)rr=r>rzrrrrs zBaseRequestHandler.__init__cCsdS)Nr)rrrrr{szBaseRequestHandler.setupcCsdS)Nr)rrrrr|szBaseRequestHandler.handlecCsdS)Nr)rrrrr}szBaseRequestHandler.finishN)rMrNrOrPrr{r|r}rrrrr s  c@s0eZdZdZd ZdZdZdZddZdd Z dS) r z4Define self.rfile and self.wfile for stream sockets.rUrNFcCsz|j|_|jdk r |jj|j|jr:|jjtjtjd|jj d|j |_ |j dkrdt |j|_n|jj d|j |_dS)NTrbrwb)r=Z connectionr1Z settimeoutdisable_nagle_algorithmrWr0Z IPPROTO_TCPZ TCP_NODELAYmakefilerbufsizerfilewbufsize _SocketWriterwfile)rrrrr{s    zStreamRequestHandler.setupc CsF|jjs.y|jjWntjk r,YnX|jj|jjdS)N)rclosedflushr0errorrYr)rrrrr} s zStreamRequestHandler.finishr^) rMrNrOrPrrr1rr{r}rrrrr s  c@s0eZdZdZddZddZddZdd Zd S) rzSimple writable BufferedIOBase implementation for a socket Does not hold data in a buffer, avoiding any need to call flush().cCs ||_dS)N)_sock)rZsockrrrrsz_SocketWriter.__init__cCsdS)NTr)rrrrwritablesz_SocketWriter.writablec Cs&|jj|t|}|jSQRXdS)N)rZsendall memoryviewnbytes)rbZviewrrrwrite"s  z_SocketWriter.writecCs |jjS)N)rrZ)rrrrrZ'sz_SocketWriter.filenoN)rMrNrOrPrrrrZrrrrrs rc@s eZdZdZddZddZdS)r z6Define self.rfile and self.wfile for datagram sockets.cCs2ddlm}|j\|_|_||j|_||_dS)Nr)BytesIO)iorr=Zpacketr0rr)rrrrrr{.s  zDatagramRequestHandler.setupcCs|jj|jj|jdS)N)r0Zsendtorgetvaluer>)rrrrr}4szDatagramRequestHandler.finishN)rMrNrOrPr{r}rrrrr *s)%rP __version__r0r%rberrnorFr ImportErrorZdummy_threadingrrr3r__all__hasattrextendrr#ZSelectSelectorrrrrr rrrrrrrrr r rr rrrrws\      n~ X.  .-