f ž _+iã@sÒdZdZddlZddlZddlZddlZddlZddlmZddl m Z gd¢Z e edƒrhe   gd¢¡e ed ƒr€e   gd ¢¡e ed ƒr’ejZnejZGd d „d ƒZGdd„deƒZGdd„deƒZe edƒrÞGdd„dƒZGdd„dƒZe edƒrGdd„deeƒZGdd„deeƒZGdd„deeƒZGdd„deeƒZe ed ƒrGdd„deƒZGd d!„d!eƒZGd"d#„d#eeƒZGd$d%„d%eeƒZGd&d'„d'ƒZGd(d)„d)eƒZGd*d+„d+eƒZ Gd,d-„d-eƒZ!dS).aqGeneric 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 saves 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)ú/Constructor. May be extended, do not override.FN)Úserver_addressÚRequestHandlerClassÚ threadingÚEventÚ_BaseServer__is_shut_downÚ_BaseServer__shutdown_request)Úselfrr©rú%/usr/lib64/python3.10/socketserver.pyÚ__init__Ès zBaseServer.__init__cCsdS©zSCalled by constructor to activate the server. May be overridden. Nr©rrrr Úserver_activateÏszBaseServer.server_activateçà?cCs˜|j ¡zvtƒL}| |tj¡|jsP| |¡}|jr:qP|rF| ¡|  ¡q"Wdƒn1sd0YWd|_|j  ¡nd|_|j  ¡0dS)zÑHandle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. NF) rÚclearÚ_ServerSelectorÚregisterÚ selectorsÚ EVENT_READrÚselectÚ_handle_request_noblockÚservice_actionsÚset)rZ poll_intervalÚselectorÚreadyrrr Ú serve_forever×s  * ÿzBaseServer.serve_forevercCsd|_|j ¡dS)zÀStops the serve_forever loop. Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will deadlock. TN)rrÚwaitr#rrr ÚshutdownôszBaseServer.shutdowncCsdS)z¡Called by the serve_forever() loop. May be overridden by a subclass / Mixin to implement any code that needs to be run during the loop. Nrr#rrr r-þszBaseServer.service_actionscCsÀ|j ¡}|dur|j}n|jdur0t||jƒ}|durBtƒ|}tƒd}| |tj¡|  |¡}|r||  ¡WdƒS|durX|tƒ}|dkrX|  ¡WdƒS1s²0YdS)zOHandle one request, possibly blocking. Respects self.timeout. Nr) ÚsocketÚ gettimeoutÚtimeoutÚminÚtimer'r(r)r*r+r,Úhandle_timeout)rr6Údeadliner/r0rrr Úhandle_requests       zBaseServer.handle_requestcCsz| ¡\}}Wnty$YdS0| ||¡r‚z| ||¡WnHtyj| ||¡| |¡Yn"| |¡‚Yn 0| |¡dS)zêHandle one request, without blocking. I assume that selector.select() has returned that the socket is readable before this function was called, so there should be no risk of blocking in get_request(). N)Ú get_requestÚOSErrorÚverify_requestÚprocess_requestÚ ExceptionÚ handle_errorÚshutdown_request©rÚrequestÚclient_addressrrr r,/s     z"BaseServer._handle_request_noblockcCsdS)zcCalled if no new request arrives within self.timeout. Overridden by ForkingMixIn. Nrr#rrr r9FszBaseServer.handle_timeoutcCsdS)znVerify the request. May be overridden. Return True if we should proceed with this request. TrrCrrr r>MszBaseServer.verify_requestcCs| ||¡| |¡dS)zVCall finish_request. Overridden by ForkingMixIn and ThreadingMixIn. N)Úfinish_requestrBrCrrr r?Us zBaseServer.process_requestcCsdS©zDCalled to clean-up the server. May be overridden. Nrr#rrr Ú server_close^szBaseServer.server_closecCs| |||¡dS)z8Finish one request by instantiating RequestHandlerClass.N)rrCrrr rFfszBaseServer.finish_requestcCs| |¡dS©z3Called to shutdown and close an individual request.N©Ú close_request©rrDrrr rBjszBaseServer.shutdown_requestcCsdS©z)Called to clean up an individual request.NrrLrrr rKnszBaseServer.close_requestcCs@tdtjdtd|tjdddl}| ¡tdtjddS)ztHandle an error gracefully. May be overridden. The default is to print a traceback and continue. z(----------------------------------------)Úfilez4Exception occurred during processing of request fromrN)ÚprintÚsysÚstderrÚ tracebackÚ print_exc)rrDrErRrrr rArsÿzBaseServer.handle_errorcCs|S©Nrr#rrr Ú __enter__szBaseServer.__enter__cGs | ¡dSrT)rH)rÚargsrrr Ú__exit__‚szBaseServer.__exit__)r%)Ú__name__Ú __module__Ú __qualname__Ú__doc__r6r!r$r1r3r-r;r,r9r>r?rHrFrBrKrArUrWrrrr r™s&+    rc@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¡|_|rPz| ¡| ¡Wn| ¡‚Yn0dS)rN)rr!r4Úaddress_familyÚ socket_typeÚ server_bindr$rH)rrrZbind_and_activaterrr r!½sÿ zTCPServer.__init__cCs8|jr|j tjtjd¡|j |j¡|j ¡|_dS)zOCalled by constructor to bind the socket. May be overridden. éN)Úallow_reuse_addressr4Ú setsockoptÚ SOL_SOCKETÚ SO_REUSEADDRÚbindrÚ getsocknamer#rrr r_ÊszTCPServer.server_bindcCs|j |j¡dSr")r4ÚlistenÚrequest_queue_sizer#rrr r$ÕszTCPServer.server_activatecCs|j ¡dSrG)r4Úcloser#rrr rHÝszTCPServer.server_closecCs |j ¡S)zMReturn socket file number. Interface required by selector. )r4Úfilenor#rrr rjåszTCPServer.filenocCs |j ¡S)zYGet the request and client address from the socket. May be overridden. )r4Úacceptr#rrr r<íszTCPServer.get_requestcCs2z| tj¡Wnty"Yn0| |¡dSrI)r3r4ÚSHUT_WRr=rKrLrrr rBõs  zTCPServer.shutdown_requestcCs | ¡dSrM)rirLrrr rKÿszTCPServer.close_requestN)T)rXrYrZr[r4ÚAF_INETr]Ú SOCK_STREAMr^rhrar!r_r$rHrjr<rBrKrrrr r†s-   rc@s>eZdZdZdZejZdZdd„Z dd„Z dd „Z d d „Z d S) rzUDP server class.Fi cCs |j |j¡\}}||jf|fSrT)r4ÚrecvfromÚmax_packet_size)rÚdataZ client_addrrrr r<szUDPServer.get_requestcCsdSrTrr#rrr r$szUDPServer.server_activatecCs| |¡dSrTrJrLrrr rBszUDPServer.shutdown_requestcCsdSrTrrLrrr rKszUDPServer.close_requestN) rXrYrZr[rar4Ú SOCK_DGRAMr^rpr<r$rBrKrrrr rsrcsVeZdZdZdZdZdZdZddœ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à|jdurdSt|jƒ|jkrpz t dd¡\}}|j |¡WqtyZ|j ¡YqtynYqpYq0|j  ¡D]`}z.|rˆdntj }t ||¡\}}|j |¡WqztyÊ|j |¡YqztyÚYqz0dS)z7Internal routine to wait for children that have exited.Néÿÿÿÿr) Úactive_childrenÚlenÚ max_childrenÚosÚwaitpidÚdiscardÚChildProcessErrorr&r=ÚcopyÚWNOHANG)rruÚ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©rƒr#rrr r9KszForkingMixIn.handle_timeoutcCs | ¡dS)zCollect the zombie child processes regularly in the ForkingMixIn. service_actions is called in the BaseServer's serve_forever loop. Nr„r#rrr r-RszForkingMixIn.service_actionscCsÄt ¡}|r8|jdurtƒ|_|j |¡| |¡dSd}z\z| ||¡d}Wntyp| ||¡Yn0Wz|  |¡Wt  |¡n2t  |¡0z|  |¡Wt  |¡0t  |¡0dS)z-Fork a new subprocess to process the request.Nr`r) rzr rwr.ÚaddrKrFr@rArBÚ_exit)rrDrEr€Ústatusrrr r?Ys&      ý zForkingMixIn.process_requestcstƒ ¡|j|jddS)Nrt)ÚsuperrHrƒÚblock_on_closer#©Ú __class__rr rHrs zForkingMixIn.server_close)rXrYrZr[r6rwryr‰rƒr9r-r?rHÚ __classcell__rrrŠr rs#rcs<eZdZdZdZdZdZdd„Zdd„Z‡fd d „Z ‡Z S) r z4Mix-in class to handle each request in a new thread.FTNc CsPz>z| ||¡Wnty0| ||¡Yn0W| |¡n | |¡0dS)zgSame as in BaseServer but as a thread. In addition, exception handling is done here. N)rFr@rArBrCrrr Úprocess_request_threadƒs  z%ThreadingMixIn.process_request_threadcCsPtj|j||fd}|j|_|jsD|jrD|jdur8g|_|j |¡| ¡dS)z*Start a new thread to process the request.)ÚtargetrVN) rÚThreadrÚdaemon_threadsÚdaemonr‰Ú_threadsÚappendÚstart)rrDrEÚtrrr r?sÿ   zThreadingMixIn.process_requestcs6tƒ ¡|jr2|j}d|_|r2|D] }| ¡q$dSrT)rˆrHr‰r’Újoin)rÚthreadsÚthreadrŠrr rH›s zThreadingMixIn.server_close) rXrYrZr[rr‰r’rr?rHrŒrrrŠr r ws  r c@s eZdZdS)rN©rXrYrZrrrr r¦órc@s eZdZdS)rNr™rrrr r§ršrc@s eZdZdS)rNr™rrrr r©ršrc@s eZdZdS)rNr™rrrr rªršrc@seZdZejZdS)rN©rXrYrZr4rr]rrrr r®src@seZdZejZdS)rNr›rrrr r±src@s eZdZdS)rNr™rrrr r´ršrc@s eZdZdS)rNr™rrrr r¶ršrc@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. cCs>||_||_||_| ¡z| ¡W| ¡n | ¡0dSrT)rDrEÚserverÚsetupÚhandleÚfinish)rrDrErœrrr r!Ês zBaseRequestHandler.__init__cCsdSrTrr#rrr rÔszBaseRequestHandler.setupcCsdSrTrr#rrr rž×szBaseRequestHandler.handlecCsdSrTrr#rrr rŸÚszBaseRequestHandler.finishN)rXrYrZr[r!rržrŸrrrr r ¸s  r c@s0eZdZdZdZdZdZdZdd„Zdd „Z dS) r z4Define self.rfile and self.wfile for stream sockets.rvrNFcCsz|j|_|jdur |j |j¡|jr:|j tjtjd¡|j  d|j ¡|_ |j dkrdt |jƒ|_n|j  d|j ¡|_dS)NTÚrbrÚwb)rDÚ connectionr6Ú settimeoutÚdisable_nagle_algorithmrbr4Ú IPPROTO_TCPÚ TCP_NODELAYÚmakefileÚrbufsizeÚrfileÚwbufsizeÚ _SocketWriterÚwfiler#rrr rûs  ÿ zStreamRequestHandler.setupcCsD|jjs,z|j ¡Wntjy*Yn0|j ¡|j ¡dSrT)r¬ÚclosedÚflushr4Úerrorrir©r#rrr rŸs zStreamRequestHandler.finish) rXrYrZr[r¨rªr6r¤rrŸrrrr r æs  r 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 ||_dSrT)Ú_sock)rÚsockrrr r!sz_SocketWriter.__init__cCsdS)NTrr#rrr Úwritablesz_SocketWriter.writablecCs>|j |¡t|ƒ}|jWdƒS1s00YdSrT)r°ÚsendallÚ memoryviewÚnbytes)rÚbÚviewrrr Úwrites  z_SocketWriter.writecCs |j ¡SrT)r°rjr#rrr rj#sz_SocketWriter.filenoN)rXrYrZr[r!r²r¸rjrrrr r«s r«c@s eZdZdZdd„Zdd„ZdS)r z6Define self.rfile and self.wfile for datagram sockets.cCs2ddlm}|j\|_|_||jƒ|_|ƒ|_dS)Nr)ÚBytesIO)Úior¹rDZpacketr4r©r¬)rr¹rrr r*s  zDatagramRequestHandler.setupcCs|j |j ¡|j¡dSrT)r4Úsendtor¬ÚgetvaluerEr#rrr rŸ0szDatagramRequestHandler.finishN)rXrYrZr[rrŸrrrr r &sr )"r[Ú __version__r4r)rzrPrrºrr8rÚ__all__ÚhasattrÚextendrr'ÚSelectSelectorrrrrr rrrrrrrrr r r«r rrrr ÚsJz     n~ X.  .-