B ‚Ž\]*iã @sædZdZddlZddlZddlZddlZddlZddlmZddl m Z dddd d d d d dg Z e edƒrxe   dddg¡e edƒr”e   ddddg¡e edƒr¦ejZnejZGdd„dƒZGdd„deƒZGdd„deƒZe edƒròGdd„dƒZGdd„dƒZe edƒr0Gdd„deeƒZGdd„deeƒZGd d „d eeƒZGd!d „d eeƒZe edƒr¤Gd"d„deƒZGd#d„deƒZGd$d„deeƒZGd%d„deeƒZGd&d „d ƒZGd'd „d eƒZGd(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.4éN)ÚBufferedIOBase)Ú monotonicÚ BaseServerÚ TCPServerÚ UDPServerÚThreadingUDPServerÚThreadingTCPServerÚBaseRequestHandlerÚStreamRequestHandlerÚDatagramRequestHandlerÚThreadingMixInÚforkÚForkingUDPServerÚForkingTCPServerÚ ForkingMixInÚAF_UNIXÚUnixStreamServerÚUnixDatagramServerÚThreadingUnixStreamServerÚThreadingUnixDatagramServerÚ PollSelectorc@sžeZdZdZdZdd„Zdd„Zd&dd „Zd d „Zd d „Z dd„Z dd„Z dd„Z dd„Z dd„Zdd„Zdd„Zdd„Zdd„Zd d!„Zd"d#„Zd$d%„ZdS)'ra¸Base 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 ||_||_t ¡|_d|_dS)z/Constructor. May be extended, do not override.FN)Úserver_addressÚRequestHandlerClassÚ threadingÚEventÚ_BaseServer__is_shut_downÚ_BaseServer__shutdown_request)Úselfrr©rú(/usr/local/lib/python3.7/socketserver.pyÚ__init__Ès zBaseServer.__init__cCsdS)zSCalled by constructor to activate the server. May be overridden. Nr)rrrrÚserver_activateÏszBaseServer.server_activateçà?c Csx|j ¡zVtƒF}| |tj¡x0|jsR| |¡}|jr)rr?r@rrrr;Us zBaseServer.process_requestcCsdS)zDCalled to clean-up the server. May be overridden. Nr)rrrrÚ server_close^szBaseServer.server_closecCs| |||¡dS)z8Finish one request by instantiating RequestHandlerClass.N)r)rr?r@rrrrAfszBaseServer.finish_requestcCs| |¡dS)z3Called to shutdown and close an individual request.N)Ú close_request)rr?rrrr>jszBaseServer.shutdown_requestcCsdS)z)Called to clean up an individual request.Nr)rr?rrrrCnszBaseServer.close_requestcCs@tdtjdtd|tjdddl}| ¡tdtjddS)ztHandle an error gracefully. May be overridden. The default is to print a traceback and continue. z(----------------------------------------)Úfilez4Exception happened during processing of request fromrN)ÚprintÚsysÚstderrÚ tracebackÚ print_exc)rr?r@rHrrrr=rs  zBaseServer.handle_errorcCs|S)Nr)rrrrÚ __enter__szBaseServer.__enter__cGs | ¡dS)N)rB)rÚargsrrrÚ__exit__‚szBaseServer.__exit__)r")Ú__name__Ú __module__Ú __qualname__Ú__doc__r3r r!r.r0r*r7r)r6r:r;rBrAr>rCr=rJrLrrrrr™s&+    c@sfeZdZdZejZejZdZ dZ ddd„Z dd„Z d d „Z d d „Zd d„Zdd„Zdd„Zdd„ZdS)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 éFTcCsTt |||¡t |j|j¡|_|rPy| ¡| ¡Wn| ¡‚YnXdS)z/Constructor. May be extended, do not override.N)rr r1Úaddress_familyÚ socket_typeÚ server_bindr!rB)rrrZbind_and_activaterrrr ½s  zTCPServer.__init__cCs8|jr|j tjtjd¡|j |j¡|j ¡|_dS)zOCalled by constructor to bind the socket. May be overridden. éN)Úallow_reuse_addressr1Ú setsockoptÚ SOL_SOCKETÚ SO_REUSEADDRÚbindrÚ getsockname)rrrrrTÊszTCPServer.server_bindcCs|j |j¡dS)zSCalled by constructor to activate the server. May be overridden. N)r1ÚlistenÚrequest_queue_size)rrrrr!ÕszTCPServer.server_activatecCs|j ¡dS)zDCalled to clean-up the server. May be overridden. N)r1Úclose)rrrrrBÝszTCPServer.server_closecCs |j ¡S)zMReturn socket file number. Interface required by selector. )r1Úfileno)rrrrr_åszTCPServer.filenocCs |j ¡S)zYGet the request and client address from the socket. May be overridden. )r1Úaccept)rrrrr8íszTCPServer.get_requestcCs4y| tj¡Wntk r$YnX| |¡dS)z3Called to shutdown and close an individual request.N)r0r1ÚSHUT_WRr9rC)rr?rrrr>õs zTCPServer.shutdown_requestcCs | ¡dS)z)Called to clean up an individual request.N)r^)rr?rrrrCÿszTCPServer.close_requestN)T)rMrNrOrPr1ÚAF_INETrRÚ SOCK_STREAMrSr]rVr rTr!rBr_r8r>rCrrrrr†s-   c@s>eZdZdZdZejZdZdd„Z dd„Z dd „Z d d „Z d S) rzUDP server class.Fi cCs |j |j¡\}}||jf|fS)N)r1ÚrecvfromÚmax_packet_size)rÚdataZ client_addrrrrr8szUDPServer.get_requestcCsdS)Nr)rrrrr!szUDPServer.server_activatecCs| |¡dS)N)rC)rr?rrrr>szUDPServer.shutdown_requestcCsdS)Nr)rr?rrrrCszUDPServer.close_requestN) rMrNrOrPrVr1Ú SOCK_DGRAMrSrer8r!r>rCrrrrrscsVeZdZdZdZdZdZdZddœdd „Zd d „Z d d „Z dd„Z ‡fdd„Z ‡Z S)rz5Mix-in class to handle each request in a new process.i,Né(TF)Úblockingc Csò|jdkrdSxht|jƒ|jkrvy t dd¡\}}|j |¡Wqtk r^|j ¡Yqtk rrPYqXqWxt|j  ¡D]f}y.|r’dntj }t ||¡\}}|j |¡Wq„tk rÖ|j |¡Yq„tk rèYq„Xq„WdS)z7Internal routine to wait for children that have exited.Néÿÿÿÿr) Úactive_childrenÚlenÚ max_childrenÚosÚwaitpidÚdiscardÚChildProcessErrorr#r9ÚcopyÚWNOHANG)rriÚpidÚ_ÚflagsrrrÚcollect_children(s&  zForkingMixIn.collect_childrencCs | ¡dS)zvWait for zombies after self.timeout seconds of inactivity. May be extended, do not override. N)rw)rrrrr6KszForkingMixIn.handle_timeoutcCs | ¡dS)zCollect the zombie child processes regularly in the ForkingMixIn. service_actions is called in the BaseServer's serve_forever loop. N)rw)rrrrr*RszForkingMixIn.service_actionscCsšt ¡}|r8|jdkrtƒ|_|j |¡| |¡dSd}z:y| ||¡d}Wn tk rr| ||¡YnXWdz|  |¡Wdt  |¡XXdS)z-Fork a new subprocess to process the request.NrUr) rnr rkr+ÚaddrCrAr<r=r>Ú_exit)rr?r@rtÚstatusrrrr;Ys     zForkingMixIn.process_requestcstƒ ¡|j|jddS)N)ri)ÚsuperrBrwÚblock_on_close)r)Ú __class__rrrBrs zForkingMixIn.server_close)rMrNrOrPr3rkrmr|rwr6r*r;rBÚ __classcell__rr)r}rrs#cs<eZdZdZdZdZdZdd„Zdd„Z‡fd d „Z ‡Z S) r z4Mix-in class to handle each request in a new thread.FTNc CsHz6y| ||¡Wn tk r2| ||¡YnXWd| |¡XdS)zgSame as in BaseServer but as a thread. In addition, exception handling is done here. N)rAr<r=r>)rr?r@rrrÚprocess_request_threadƒs z%ThreadingMixIn.process_request_threadcCsPtj|j||fd}|j|_|jsD|jrD|jdkr8g|_|j |¡| ¡dS)z*Start a new thread to process the request.)ÚtargetrKN) rÚThreadrÚdaemon_threadsÚdaemonr|Ú_threadsÚappendÚstart)rr?r@Útrrrr;s    zThreadingMixIn.process_requestcs:tƒ ¡|jr6|j}d|_|r6x|D] }| ¡q&WdS)N)r{rBr|r„Újoin)rÚthreadsÚthread)r}rrrB›s  zThreadingMixIn.server_close) rMrNrOrPr‚r|r„rr;rBr~rr)r}rr ws  c@s eZdZdS)rN)rMrNrOrrrrr¦sc@s eZdZdS)rN)rMrNrOrrrrr§sc@s eZdZdS)rN)rMrNrOrrrrr©sc@s eZdZdS)rN)rMrNrOrrrrrªsc@seZdZejZdS)rN)rMrNrOr1rrRrrrrr®sc@seZdZejZdS)rN)rMrNrOr1rrRrrrrr±sc@s eZdZdS)rN)rMrNrOrrrrr´sc@s eZdZdS)rN)rMrNrOrrrrr¶sc@s0eZdZdZdd„Zdd„Zdd„Zdd „Zd S) r a¥Base 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. cCs6||_||_||_| ¡z | ¡Wd| ¡XdS)N)r?r@ÚserverÚsetupÚhandleÚfinish)rr?r@r‹rrrr Ês zBaseRequestHandler.__init__cCsdS)Nr)rrrrrŒÔszBaseRequestHandler.setupcCsdS)Nr)rrrrr×szBaseRequestHandler.handlecCsdS)Nr)rrrrrŽÚszBaseRequestHandler.finishN)rMrNrOrPr rŒrrŽrrrrr ¸s  c@s0eZdZdZdZdZdZdZdd„Zdd „Z dS) r z4Define self.rfile and self.wfile for stream sockets.rjrNFcCsz|j|_|jdk r |j |j¡|jr:|j tjtjd¡|j  d|j ¡|_ |j dkrdt |jƒ|_n|j  d|j ¡|_dS)NTÚrbrÚwb)r?Ú connectionr3Ú settimeoutÚdisable_nagle_algorithmrWr1Ú IPPROTO_TCPÚ TCP_NODELAYÚmakefileÚrbufsizeÚrfileÚwbufsizeÚ _SocketWriterÚwfile)rrrrrŒûs    zStreamRequestHandler.setupcCsF|jjs.y|j ¡Wntjk r,YnX|j ¡|j ¡dS)N)r›ÚclosedÚflushr1Úerrorr^r˜)rrrrrŽs zStreamRequestHandler.finish) rMrNrOrPr—r™r3r“rŒrŽrrrrr æs  c@s0eZdZdZdd„Zdd„Zdd„Zdd „Zd S) ršz‚Simple writable BufferedIOBase implementation for a socket Does not hold data in a buffer, avoiding any need to call flush().cCs ||_dS)N)Ú_sock)rÚsockrrrr sz_SocketWriter.__init__cCsdS)NTr)rrrrÚwritablesz_SocketWriter.writablec Cs&|j |¡t|ƒ}|jSQRXdS)N)rŸÚsendallÚ memoryviewÚnbytes)rÚbÚviewrrrÚwrites  z_SocketWriter.writecCs |j ¡S)N)rŸr_)rrrrr_#sz_SocketWriter.filenoN)rMrNrOrPr r¡r§r_rrrrršs ršc@s eZdZdZdd„Zdd„ZdS)r z6Define self.rfile and self.wfile for datagram sockets.cCs2ddlm}|j\|_|_||jƒ|_|ƒ|_dS)Nr)ÚBytesIO)Úior¨r?Zpacketr1r˜r›)rr¨rrrrŒ*s  zDatagramRequestHandler.setupcCs|j |j ¡|j¡dS)N)r1Úsendtor›Úgetvaluer@)rrrrrŽ0szDatagramRequestHandler.finishN)rMrNrOrPrŒrŽrrrrr &s)"rPÚ __version__r1r&rnrFrr©rr5rÚ__all__ÚhasattrÚextendrr$ÚSelectSelectorrrrrr rrrrrrrrr r ršr rrrrÚwsT     n~ X.  .-