Qfl\dZdZddlZddlZddlZddlZddlZddlmZddl m Z gdZ e edre jgde ed r/e jgd e edre jd d ge ed r ejZn ej ZGddZGddeZGddeZe edr GddZGddeZGddZGddZe edrGddeeZGddeeZGd d!eeZGd"d#eeZe ed rOGd$d%eZGd&d'eZGd(d)eeZGd*d+eeZ e edrGd,d eeZ!Gd-d eeZ"Gd.d/Z#Gd0d1e#Z$Gd2d3eZ%Gd4d5e#Z&y)6aqGeneric 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.4N)BufferedIOBase) monotonic) BaseServer TCPServer UDPServerThreadingUDPServerThreadingTCPServerBaseRequestHandlerStreamRequestHandlerDatagramRequestHandlerThreadingMixInfork)ForkingUDPServerForkingTCPServer ForkingMixInAF_UNIX)UnixStreamServerUnixDatagramServerThreadingUnixStreamServerThreadingUnixDatagramServerForkingUnixStreamServerForkingUnixDatagramServer PollSelectorc|eZdZdZdZdZdZddZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZy)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 - allow_reuse_port Instance variables: - RequestHandlerClass - socket Nc`||_||_tj|_d|_y)/Constructor. May be extended, do not override.FN)server_addressRequestHandlerClass threadingEvent_BaseServer__is_shut_down_BaseServer__shutdown_request)selfrrs 3/opt/alt/python312/lib64/python3.12/socketserver.py__init__zBaseServer.__init__s),#6 'oo/"'cyzSCalled by constructor to activate the server. May be overridden. Nr#s r$server_activatezBaseServer.server_activate r&c|jj t5}|j|tj |j sM|j|}|j rn/|r|j|j|j sMdddd|_|jjy#1swY+xYw#d|_|jjwxYw)zHandle 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_ServerSelectorregister selectors EVENT_READr"select_handle_request_noblockservice_actionsset)r# poll_intervalselectorreadys r$ serve_foreverzBaseServer.serve_forevers !!# & !"h!!$ (<(<=11$OOM:E..446((*11#',D #    # # %#"',D #    # # %s# CA9C  C CC#C9cFd|_|jjy)zStops 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)r"r!waitr*s r$shutdownzBaseServer.shutdowns#'   "r&cy)zCalled by the serve_forever() loop. May be overridden by a subclass / Mixin to implement any code that needs to be run during the loop. Nr)r*s r$r5zBaseServer.service_actionsr,r&c|jj}| |j}n"|jt||j}| t |z}t 5}|j |tj |j|r|jcdddS|+t z }|dkr|jcdddSX#1swYyxYw)zOHandle one request, possibly blocking. Respects self.timeout. Nr) socket gettimeouttimeoutmintimer/r0r1r2r3r4handle_timeout)r#rBdeadliner8s r$handle_requestzBaseServer.handle_requests++((* ?llG \\ %'4<<0G  v'H (   dI$8$8 9??7+779 9 9*"*TV"3"Q;#'#6#6#8 9 9 s%AC1#CCC(c@ |j\}}|j||r |j||y|j |y#t$rYywxYw#t$r&|j |||j |Yy|j |xYw)zHandle 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_requestOSErrorverify_requestprocess_request Exception handle_errorshutdown_requestr#requestclient_addresss r$r4z"BaseServer._handle_request_noblock1s &*&6&6&8 #G^   w 7 $$Wn=  ! !' *     /!!'>:%%g. %%g.s"A A AA,B Bcy)zcCalled if no new request arrives within self.timeout. Overridden by ForkingMixIn. Nr)r*s r$rEzBaseServer.handle_timeoutHs r&cy)znVerify the request. May be overridden. Return True if we should proceed with this request. Tr)rPs r$rKzBaseServer.verify_requestOs r&cJ|j|||j|y)zVCall finish_request. Overridden by ForkingMixIn and ThreadingMixIn. N)finish_requestrOrPs r$rLzBaseServer.process_requestWs" G^4 g&r&cyzDCalled to clean-up the server. May be overridden. Nr)r*s r$ server_closezBaseServer.server_close`r,r&c*|j|||y)z8Finish one request by instantiating RequestHandlerClass.N)rrPs r$rVzBaseServer.finish_requesths   .$?r&c&|j|yz3Called to shutdown and close an individual request.N close_requestr#rQs r$rOzBaseServer.shutdown_requestl 7#r&cyz)Called to clean up an individual request.Nr)r_s r$r^zBaseServer.close_requestp r&ctdtjtd|tjddl}|j tdtjy)ztHandle an error gracefully. May be overridden. The default is to print a traceback and continue. z(----------------------------------------)filez4Exception occurred during processing of request fromrN)printsysstderr traceback print_exc)r#rQrRris r$rNzBaseServer.handle_errortsC f3::& D  - f3::&r&c|SNr)r*s r$ __enter__zBaseServer.__enter__s r&c$|jyrl)rY)r#argss r$__exit__zBaseServer.__exit__s r&)g?)__name__ __module__ __qualname____doc__rBr%r+r:r=r5rGr4rErKrLrYrVrOr^rNrmrpr)r&r$rrse*XG( &:# &9:+. ' @$  'r&rc~eZdZdZej ZejZdZ dZ dZ d dZ dZ dZdZdZd Zd Zd Zy )raJBase 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 - allow_reuse_port Instance variables: - server_address - RequestHandlerClass - socket Fctj|||tj|j|j|_|r" |j |j yy#|jxYw)rN)rr%r@address_family socket_type server_bindr+rY)r#rrbind_and_activates r$r%zTCPServer.__init__sqD.2EFmmD$7$7$($4$46    "$$&  !!#s A,,A?c|jrIttdr9|jjtjtj d|j rIttdr9|jjtjtjd|jj|j|jj|_ y)zOCalled by constructor to bind the socket. May be overridden. SO_REUSEADDR SO_REUSEPORTN) allow_reuse_addresshasattrr@ setsockopt SOL_SOCKETr}allow_reuse_portrbindr getsocknamer*s r$rzzTCPServer.server_binds  # #(G KK " "6#4#4f6I6I1 M  WV^%D KK " "6#4#4f6I6I1 M ,,-"kk557r&cN|jj|jyr()r@listenrequest_queue_sizer*s r$r+zTCPServer.server_activates 4223r&c8|jjyrX)r@closer*s r$rYzTCPServer.server_closes r&c6|jjS)zMReturn socket file number. Interface required by selector. )r@filenor*s r$rzTCPServer.fileno {{!!##r&c6|jjS)zYGet the request and client address from the socket. May be overridden. )r@acceptr*s r$rIzTCPServer.get_requestrr&c |jtj|j |y#t$rYwxYwr\)r=r@SHUT_WRrJr^r_s r$rOzTCPServer.shutdown_requests?    V^^ , 7#   s 3 ??c$|jyrb)rr_s r$r^zTCPServer.close_requests  r&N)T)rqrrrsrtr@AF_INETrx SOCK_STREAMryrrrr%rzr+rYrrIrOr^r)r&r$rrsX,\^^N$$K  84$$$r&rcLeZdZdZdZdZejZdZ dZ dZ dZ dZ y) rzUDP server class.Fi cr|jj|j\}}||jf|fSrl)r@recvfrommax_packet_size)r#data client_addrs r$rIzUDPServer.get_requests5 KK001E1EFkdkk"K//r&cyrlr)r*s r$r+zUDPServer.server_activatercr&c&|j|yrlr]r_s r$rOzUDPServer.shutdown_requestr`r&cyrlr)r_s r$r^zUDPServer.close_request#rcr&N)rqrrrsrtrrr@ SOCK_DGRAMryrrIr+rOr^r)r&r$rr s5##KO0 $ r&rcPeZdZdZdZdZdZdZdddZd Z d Z d Z fd Z xZ S) rz5Mix-in class to handle each request in a new process.i,N(TFblockingc|jyt|j|jk\rX tjdd\}}|jj |t|j|jk\rX|jjD]K} |rdntj}tj||\}}|jj |My#t $r|jjYt$rYwxYw#t $r|jj |Yt$rYwxYw)z7Internal routine to wait for children that have exited.Nr) active_childrenlen max_childrenoswaitpiddiscardChildProcessErrorr.rJcopyWNOHANG)r#rpid_flagss r$collect_childrenzForkingMixIn.collect_children1s(##+d**+t/@/@@ZZA.FC((005d**+t/@/@@++002 !)ArzzEZZU3FC((005 3)1((..0)6((005s04C1&AD$1#D!D! D!$$E EEc$|jy)zvWait for zombies after self.timeout seconds of inactivity. May be extended, do not override. Nrr*s r$rEzForkingMixIn.handle_timeoutT  ! ! #r&c$|jy)zCollect the zombie child processes regularly in the ForkingMixIn. service_actions is called in the BaseServer's serve_forever loop. Nrr*s r$r5zForkingMixIn.service_actions[rr&c>tj}|rH|jt|_|jj ||j |yd} |j ||d} |j|tj|y#t$r|j||YEwxYw#tj|wxYw# |j|tj|w#tj|wxYwxYw)z-Fork a new subprocess to process the request.Nr~r) rrrr6addr^rVrMrNrO_exit)r#rQrRrstatuss r$rLzForkingMixIn.process_requestbs'')C''/+.5D($$((-""7+ )''@F)--g6( !?%%g~>? ()--g6((sH"B7B?B<9C;B<<C?CDD,DDDcZt||j|jy)Nr)superrYrblock_on_closer# __class__s r$rYzForkingMixIn.server_close{s% G "  ! !4+>+> ! ?r&)rqrrrsrtrBrrrrrEr5rLrY __classcell__rs@r$rr(s>C /4! F $ $ )2 @ @r&rc4eZdZdZfdZdZdZdZxZS)_Threadsz2 Joinable list of all non-daemon threads. c^|j|jryt| |yrl)reapdaemonrappend)r#threadrs r$rz_Threads.appends" ==  vr&cg|ddc|dd}|Srlr))r#results r$pop_allz_Threads.pop_allsd1gQ r&cN|jD]}|jyrl)rjoinr#rs r$rz _Threads.joinsllnF KKM%r&cd|D|ddy)Nc3BK|]}|js|ywrl)is_alive).0rs r$ z _Threads.reap..sBf0A6sr)r*s r$rz _Threads.reapsBBQr&) rqrrrsrtrrrrrrs@r$rrs Cr&rceZdZdZdZdZy) _NoThreadsz) Degenerate version of _Threads. cyrlr)rs r$rz_NoThreads.append r&cyrlr)r*s r$rz_NoThreads.joinrr&N)rqrrrsrtrrr)r&r$rrs  r&rcDeZdZdZdZdZeZdZdZ fdZ xZ S)r z4Mix-in class to handle each request in a new thread.FTc |j|||j|y#t$r|j||Y/wxYw#|j|wxYw)zgSame as in BaseServer but as a thread. In addition, exception handling is done here. N)rVrMrNrOrPs r$process_request_threadz%ThreadingMixIn.process_request_threadsY  +    8  ! !' * 7   g~ 6 7  ! !' *s!&AAAAAc |jr#t|jdtt j |j ||f}|j|_|jj||jy)z*Start a new thread to process the request._threads)targetroN) rvars setdefaultrrThreadrdaemon_threadsrrrstart)r#rQrRts r$rLzThreadingMixIn.process_requestsi    J ! !*hj 9   d&A&A%,n$= ?&& Q  r&cVt||jjyrl)rrYrrrs r$rYzThreadingMixIn.server_closes  r&) rqrrrsrtrrrrrrLrYrrs@r$r r s/>NN|H +r&r c eZdZy)rNrqrrrsr)r&r$rrr&rc eZdZy)rNrr)r&r$rrrr&rc eZdZy)rNrr)r&r$rrrr&rc eZdZy)r Nrr)r&r$r r rr&r c$eZdZejZy)rNrqrrrsr@rrxr)r&r$rr r&rc$eZdZejZy)rNrr)r&r$rrrr&rc eZdZy)rNrr)r&r$rrrr&rc eZdZy)rNrr)r&r$rrrr&rc eZdZy)rNrr)r&r$rrrr&c eZdZy)rNrr)r&r$rrrr&c(eZdZdZdZdZdZdZy)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||_||_||_|j |j |j y#|j wxYwrl)rQrRserversetuphandlefinish)r#rQrRrs r$r%zBaseRequestHandler.__init__sB ,    KKM KKMDKKMs AAcyrlr)r*s r$rzBaseRequestHandler.setuprr&cyrlr)r*s r$rzBaseRequestHandler.handlerr&cyrlr)r*s r$rzBaseRequestHandler.finishrr&N)rqrrrsrtr%rrrr)r&r$r r s    r&r c,eZdZdZdZdZdZdZdZdZ y)r z4Define self.rfile and self.wfile for stream sockets.rrNFc|j|_|j%|jj|j|jr9|jj t jt jd|jjd|j|_ |jdk(rt|j|_y|jjd|j|_y)NTrbrwb)rQ connectionrB settimeoutdisable_nagle_algorithmrr@ IPPROTO_TCP TCP_NODELAYmakefilerbufsizerfilewbufsize _SocketWriterwfiler*s r$rzStreamRequestHandler.setup$s,, << # OO & &t|| 4  ' ' OO & &v'9'9'-'9'94 A__--dDMMB ==A &t7DJ11$ FDJr&c|jjs |jj|jj |j j y#tj$rYJwxYwrl)r closedflushr@errorrrr*s r$rzStreamRequestHandler.finish1s`zz      "   <<  sA''A=<A=) rqrrrsrtrr rBrrrr)r&r$r r s+>HHG$ G r&r c(eZdZdZdZdZdZdZy)r zSimple writable BufferedIOBase implementation for a socket Does not hold data in a buffer, avoiding any need to call flush().c||_yrl)_sock)r#socks r$r%z_SocketWriter.__init__As  r&cy)NTr)r*s r$writablez_SocketWriter.writableDsr&c|jj|t|5}|jcdddS#1swYyxYwrl)rsendall memoryviewnbytes)r#bviews r$writez_SocketWriter.writeGs3 1 ]d;;  ]]s =Ac6|jjSrl)rrr*s r$rz_SocketWriter.filenoLszz  ""r&N)rqrrrsrtr%rrrr)r&r$r r <sJ #r&r ceZdZdZdZdZy)r z6Define self.rfile and self.wfile for datagram sockets.cddlm}|j\|_|_||j|_||_y)Nr)BytesIO)ior rQpacketr@rr )r#r s r$rzDatagramRequestHandler.setupSs0#'<<  T[T[[) Y r&c|jj|jj|jyrl)r@sendtor getvaluerRr*s r$rzDatagramRequestHandler.finishYs) 4::..0$2E2EFr&N)rqrrrsrtrrr)r&r$r r Os@ Gr&r )'rt __version__r@r1rrgrr!rrDr__all__rextendrr/SelectSelectorrrrrlistrrr rrrr rrrrrrr r r r r)r&r$r+svt  " 7 2v NNJK 69 NN34r613NOP 9n%,,O..OjjZ@ @F  8 2vU@U@pCtC,  %%P 2v9<99<99999 69(9((Y(LN4DKOn6HOr6Kl4DKO 6HO# # \+-+Z#N#& G/ Gr&