U kg@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZz ddlZWnek rdZYnXddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddl m!Z!dZ"dZ#dZ$e%e dZ&dZ'e(Z)ddZ*ddZ+ddZ,d+ddZ-d,ddZ.dd Z/e%e d!rd"d#Z0nd$d#Z0Gd%d&d&ej1Z2Gd'd(d(ej3Z4Gd)d*d*ej5Z6dS)-aBase implementation of event loop. The event loop can be broken up into a multiplexer (the part responsible for notifying us of I/O events) and the event loop proper, which wraps a multiplexer with functionality for scheduling callbacks, immediately or at a given time in the future. Whenever a public API takes a callback, subsequent positional arguments will be passed to the callback if/when it is called. This avoids the proliferation of trivial lambdas implementing closures. Keyword arguments for the callback are not supported; this is a conscious design decision, leaving the door open for keyword arguments to modify the meaning of the API call itself. N) constants) coroutines)events) exceptions)futures) protocols)sslproto) staggered)tasks) transports)trsock)logger) BaseEventLoopdg?AF_INET6iQcCs0|j}tt|ddtjr$t|jSt|SdS)N__self__)Z _callback isinstancegetattrr Taskreprrstr)handlecbr)/usr/lib/python3.8/asyncio/base_events.py_format_handleJs rcCs(|tjkrdS|tjkrdSt|SdS)Nzz) subprocessPIPESTDOUTr)fdrrr _format_pipeSs   r!cCsLttdstdn4z|tjtjdWntk rFtdYnXdS)N SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)hasattrsocket ValueError setsockopt SOL_SOCKETr"OSErrorsockrrr_set_reuseport\s   r+c CsttdsdS|dtjtjhks(|dkr,dS|tjkr>tj}n|tjkrPtj}ndS|dkrbd}nXt|trz|dkrzd}n@t|tr|dkrd}n(z t |}Wnt t fk rYdSX|tj krtj g}tr|tjn|g}t|tr|d}d|krdS|D]t}zVt||trJ|tjkrJ|||d||||ffWS|||d||ffWSWntk rzYnXq dS)N inet_ptonrZidna%)r#r$ IPPROTO_TCPZ IPPROTO_UDP SOCK_STREAM SOCK_DGRAMrbytesrint TypeErrorr% AF_UNSPECAF_INET _HAS_IPv6appendrdecoder,r() hostportfamilytypeprotoZflowinfoZscopeidZafsafrrr _ipaddr_infogsN          rAcCst}|D]*}|d}||kr(g||<|||q t|}g}|dkr|||dd|d|dd|d=|ddtjtj |D|S)z-Interleave list of addrinfo tuples by family.rrNcss|]}|dk r|VqdSNr).0arrr sz(_interleave_addrinfos..) collections OrderedDictr9listvaluesextend itertoolschain from_iterable zip_longest)Z addrinfosZfirst_address_family_countZaddrinfos_by_familyaddrr=Zaddrinfos_listsZ reorderedrrr_interleave_addrinfoss"  rPcCs4|s"|}t|ttfr"dSt|dSrB) cancelled exceptionr SystemExitKeyboardInterruptrZ _get_loopstop)futexcrrr_run_until_complete_cbs rX TCP_NODELAYcCs@|jtjtjhkr<|jtjkr<|jtjkr<|tjtj ddSNr) r=r$r7rr>r1r?r0r&rYr)rrr _set_nodelays   r[cCsdSrBrr)rrrr[sc@sTeZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ dS)_SendfileFallbackProtocolcCsht|tjstd||_||_||_|j |_ | | ||j r^|jj |_nd|_dS)Nz.transport should be _FlowControlMixin instance)rr Z_FlowControlMixinr5 _transportZ get_protocol_protoZ is_reading_should_resume_readingZ_protocol_paused_should_resume_writing pause_reading set_protocol_loop create_future_write_ready_fut)selftransprrr__init__s    z"_SendfileFallbackProtocol.__init__cs2|jrtd|j}|dkr$dS|IdHdS)NzConnection closed by peer)r] is_closingConnectionErrorre)rfrVrrrdrains  z_SendfileFallbackProtocol.draincCs tddS)Nz?Invalid state: connection should have been established already. RuntimeError)rf transportrrrconnection_madesz)_SendfileFallbackProtocol.connection_madecCs@|jdk r0|dkr$|jtdn |j||j|dS)NzConnection is closed by peer)reZ set_exceptionrjr^connection_lost)rfrWrrrrps  z)_SendfileFallbackProtocol.connection_lostcCs |jdk rdS|jj|_dSrB)rer]rcrdrfrrr pause_writings z'_SendfileFallbackProtocol.pause_writingcCs$|jdkrdS|jdd|_dS)NF)re set_resultrqrrrresume_writings  z(_SendfileFallbackProtocol.resume_writingcCs tddSNz'Invalid state: reading should be pausedrl)rfdatarrr data_receivedsz'_SendfileFallbackProtocol.data_receivedcCs tddSrurlrqrrr eof_receivedsz&_SendfileFallbackProtocol.eof_receivedcsF|j|j|jr|j|jdk r2|j|jrB|jdSrB) r]rbr^r_resume_readingrecancelr`rtrqrrrrestores   z!_SendfileFallbackProtocol.restoreN) __name__ __module__ __qualname__rhrkrorprrrtrwrxr{rrrrr\s r\c@sxeZdZddZddZddZddZd d Zd d Zd dZ ddZ e ddZ ddZ ddZddZddZdS)ServercCs@||_||_d|_g|_||_||_||_||_d|_d|_ dS)NrF) rc_sockets _active_count_waiters_protocol_factory_backlog _ssl_context_ssl_handshake_timeout_serving_serving_forever_fut)rfloopsocketsprotocol_factoryZ ssl_contextbacklogssl_handshake_timeoutrrrrhszServer.__init__cCsd|jjd|jdS)N) __class__r|rrqrrr__repr__ szServer.__repr__cCs |jdk st|jd7_dSrZ)rAssertionErrorrrqrrr_attach#szServer._attachcCs<|jdkst|jd8_|jdkr8|jdkr8|dS)Nrr)rrr_wakeuprqrrr_detach'szServer._detachcCs,|j}d|_|D]}|s||qdSrB)rdoners)rfwaiterswaiterrrrr-s zServer._wakeupc CsJ|jr dSd|_|jD].}||j|j|j||j||j|jqdS)NT) rrZlistenrrc_start_servingrrr)rfr*rrrr4s  zServer._start_servingcCs|jSrB)rcrqrrrget_loop>szServer.get_loopcCs|jSrB)rrqrrr is_servingAszServer.is_servingcCs"|jdkrdStdd|jDS)Nrcss|]}t|VqdSrB)r ZTransportSocket)rCsrrrrEHsz!Server.sockets..)rtuplerqrrrrDs zServer.socketscCsn|j}|dkrdSd|_|D]}|j|qd|_|jdk rX|jsX|jd|_|jdkrj|dS)NFr) rrcZ _stop_servingrrrrzrr)rfrr*rrrcloseJs   z Server.closecs"|tjd|jdIdHdS)Nrr)rr sleeprcrqrrr start_serving]szServer.start_servingc s|jdk rtd|d|jdkr4td|d||j|_zLz|jIdHWn6tjk rz|| IdHW5XYnXW5d|_XdS)Nzserver z, is already being awaited on serve_forever()z is closed) rrmrrrcrdrZCancelledErrorr wait_closedrqrrr serve_forevercs     zServer.serve_forevercs<|jdks|jdkrdS|j}|j||IdHdSrB)rrrcrdr9)rfrrrrrxs   zServer.wait_closedN)r|r}r~rhrrrrrrrpropertyrrrrrrrrrrs   rc @sPeZdZddZddZddZddd d Zd d Zd dZddddddZ ddddddddddZ dddZ dddZ dddZ dddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zejfd7d8Zd9d:Zd;d<Zdd=d>d?Z dd=d@dAZ!dd=dBdCZ"dDdEZ#dFdGZ$dHdIZ%dd=dJdKZ&dLdMZ'dNdOZ(dPdQZ)dRdRdRdRdSdTdUZ*ddVdWZ+dddXdYdZZ,d[d\Z-d]d^Z.d_d`Z/ddadbZ0dddRdRdRdddddddc dddeZ1ddfdgZ2dddXdhdiZ3djdkZ4dldmZ5ddddndodpZ6ddRdRdRe7ddddqdrdsZ8dRe9j:dRdRdSdtduZ;dvdwZddxddddddy dzd{Z?ddd|d}d~Z@ddZAddZBddZCeDjEeDjEeDjEdddRdddd ddZFeDjEeDjEeDjEdddRdddd ddZGddZHddZIddZJddZKddZLddZMddZNddZOddZPddZQddZRdS)rcCsd|_d|_d|_t|_g|_d|_d|_d|_ t dj |_ d|_|td|_d|_d|_d|_d|_t|_d|_dS)NrF monotonicg?)_timer_cancelled_count_closed _stoppingrFdeque_ready _scheduled_default_executorZ _internal_fds _thread_idtimeget_clock_infoZ resolution_clock_resolution_exception_handler set_debugrZ_is_debug_modeslow_callback_duration_current_handle _task_factory"_coroutine_origin_tracking_enabled&_coroutine_origin_tracking_saved_depthweakrefZWeakSet _asyncgens_asyncgens_shutdown_calledrqrrrrhs$  zBaseEventLoop.__init__c Cs.d|jjd|d|d|d S)Nrz running=z closed=z debug=r)rr| is_running is_closed get_debugrqrrrrs,zBaseEventLoop.__repr__cCs tj|dS)z,Create a Future object attached to the loop.r)rZFuturerqrrrrdszBaseEventLoop.create_futureN)namecCsN||jdkr2tj|||d}|jrJ|jd=n|||}t|||S)zDSchedule a coroutine object. Return a task object. N)rr) _check_closedrr r_source_tracebackZ_set_task_name)rfcororZtaskrrr create_tasks    zBaseEventLoop.create_taskcCs"|dk rt|std||_dS)awSet a task factory that will be used by loop.create_task(). If factory is None the default task factory will be set. If factory is a callable, it should have a signature matching '(loop, coro)', where 'loop' will be a reference to the active event loop, 'coro' will be a coroutine object. The callable must return a Future. Nz'task factory must be a callable or None)callabler5r)rffactoryrrrset_task_factorys zBaseEventLoop.set_task_factorycCs|jS)zsz4BaseEventLoop.shutdown_asyncgens..)Zreturn_exceptionsrz;an error occurred during closing of asynchronous generator )messagerRZasyncgen) rlenrrHclearr gatherzipr Exceptioncall_exception_handler)rfZ closing_agensZresultsresultrrrrshutdown_asyncgens s"     z BaseEventLoop.shutdown_asyncgenscCs(|rtdtdk r$tddS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running)rrmrZ_get_running_looprqrrr_check_running&s  zBaseEventLoop._check_runningc Cs||||jt|_t}tj |j |j dz t |||j rLq^qLW5d|_ d|_t d|dtj |XdS)zRun until stop() is called.) firstiter finalizerFN)rr_set_coroutine_origin_tracking_debug threading get_identrsysget_asyncgen_hooksset_asyncgen_hooksrrrrZ_set_running_loop _run_once)rfZold_agen_hooksrrr run_forever-s$     zBaseEventLoop.run_foreverc Cs||t| }tj||d}|r4d|_|tz|jd=|S)aTArrange for a callback to be called as soon as possible. This operates as a FIFO queue: callbacks are called in the order in which they are registered. Each callback will be called exactly once. Any positional arguments after the callback will be passed to the callback when it is called. call_soonr)rrrr _call_soonrrfrr rrrrrrs  zBaseEventLoop.call_sooncCsDt|st|r$td|dt|s@td|d|dS)Nzcoroutines cannot be used with z()z"a callable object was expected by z(), got )rZ iscoroutineZiscoroutinefunctionr5r)rfrmethodrrrrs  zBaseEventLoop._check_callbackcCs.t||||}|jr|jd=|j||S)Nr)rHandlerrr9)rfrrr rrrrrs  zBaseEventLoop._call_sooncCs,|jdkrdSt}||jkr(tddS)aoCheck that the current thread is the thread running the event loop. Non-thread-safe methods of this class make this assumption and will likely behave incorrectly when the assumption is violated. Should only be called when (self._debug == True). The caller is responsible for checking this condition for performance reasons. NzMNon-thread-safe operation invoked on an event loop other than the current one)rrrrm)rfZ thread_idrrrrs  zBaseEventLoop._check_threadcGsB||jr||d||||}|jr6|jd=||S)z"Like call_soon(), but thread-safe.rr)rrrrrrrrrrrs z"BaseEventLoop.call_soon_threadsafecGsZ||jr||d|dkr@|j}|dkr@tj}||_tj|j|f||dS)Nrun_in_executorr) rrrr concurrentrThreadPoolExecutorZ wrap_futureZsubmit)rfr funcrrrrrs  zBaseEventLoop.run_in_executorcCs&t|tjjstdtd||_dS)Nz{Using the default executor that is not an instance of ThreadPoolExecutor is deprecated and will be prohibited in Python 3.9)rrrrrrDeprecationWarningrr rrrset_default_executorsz"BaseEventLoop.set_default_executorc Cs|d|g}|r$|d||r8|d||rL|d||r`|d|d|}td||}t||||||} ||} d|d | d d d | }| |jkrt|n t|| S) N:zfamily=ztype=zproto=zflags=, zGet address info %szGetting address info z took g@@z.3fzms: ) r9joinrr rr$ getaddrinforinfo) rfr;r<r=r>r?flagsmsgt0addrinfodtrrr_getaddrinfo_debugs&      z BaseEventLoop._getaddrinfo_debugrr=r>r?r)c s2|jr|j}ntj}|d|||||||IdHSrB)rr.r$r'r)rfr;r<r=r>r?r)Z getaddr_funcrrrr'2szBaseEventLoop.getaddrinfocs|dtj||IdHSrB)rr$ getnameinfo)rfZsockaddrr)rrrr0<s zBaseEventLoop.getnameinfo)fallbackc s|jr|dkrtd|||||z|||||IdHWStjk rl}z |s\W5d}~XYnX|||||IdHS)Nrzthe socket must be non-blocking)rZ gettimeoutr%_check_sendfile_params_sock_sendfile_nativerSendfileNotAvailableError_sock_sendfile_fallback)rfr*fileoffsetcountr1rWrrr sock_sendfile@s zBaseEventLoop.sock_sendfilecstd|ddS)Nz-syscall sendfile is not available for socket z and file {file!r} combinationrr4rfr*r6r7r8rrrr3Ns z#BaseEventLoop._sock_sendfile_nativec s|r|||rt|tjntj}t|}d}zt|rNt|||}|dkrNqt|d|}|d|j|IdH} | szq| ||d| IdH|| 7}q2|WS|dkrt|dr|||XdS)Nrseek) r<minrZ!SENDFILE_FALLBACK_READBUFFER_SIZE bytearrayr# memoryviewrreadintoZ sock_sendall) rfr*r6r7r8 blocksizebuf total_sentviewreadrrrr5Us,  z%BaseEventLoop._sock_sendfile_fallbackcCsdt|ddkrtd|jtjks,td|dk rbt|tsLtd||dkrbtd|t|tsztd||dkrtd|dS)Nbmodez$file should be opened in binary modez+only SOCK_STREAM type sockets are supportedz+count must be a positive integer (got {!r})rz0offset must be a non-negative integer (got {!r})) rr%r>r$r1rr4r5formatr;rrrr2os2   z$BaseEventLoop._check_sendfile_paramsc s@g}|||\}}}}} d} ztj|||d} | d|dk r|D]r\}}}}} z| | WqWqHtk r} z0d| d| j} t| j| } || W5d} ~ XYqHXqH|| | | IdH| WStk r} z"|| | dk r | W5d} ~ XYn | dk r4| YnXdS)z$Create, bind and connect one socket.Nr=r>r?Fz*error while attempting to bind on address : ) r9r$ setblockingbindr(strerrorlowererrnopop sock_connectr)rfrZ addr_infoZlocal_addr_infosZ my_exceptionsr=Ztype_r?_rr*ZladdrrWr*rrr _connect_socks:        zBaseEventLoop._connect_sock) sslr=r?r)r* local_addrrrhappy_eyeballs_delay interleavec  sl| dk r|std| dkr0|r0|s,td|} | dk rD|sDtd| dk rX| dkrXd} |dk sj|dk r|dk rztdj||f|tj||dIdH}|std| dk r܈j| |tj||dIdHstdnd| rt|| }g| dkrH|D]D}z |IdH}WqvWntk r@YqYnXqn.tjfd d |D| d IdH\}}}|dkr d d Dt dkrdnJt dt fdd Dr҈dtd d dd Dn.|dkrtd|jtjkr td|j|||| | dIdH\}}jrd|d}td|||||||fS)aConnect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. Nz+server_hostname is only meaningful with sslz:You must set server_hostname when using ssl without a host1ssl_handshake_timeout is only meaningful with sslr8host/port and sock can not be specified at the same timer=r>r?r)r!getaddrinfo() returned empty listc3s |]}tj|VqdSrB) functoolspartialrS)rCr,)r laddr_infosrfrrrEs z2BaseEventLoop.create_connection..rcSsg|]}|D]}|q qSrr)rCsubrWrrrrsz3BaseEventLoop.create_connection..rc3s|]}t|kVqdSrBrrCrW)modelrrrEszMultiple exceptions: {}r%css|]}t|VqdSrBr`rarrrrE sz5host and port was not specified and no sock specified"A Stream Socket was expected, got )rr$z%r connected to %s:%r: (%r, %r))r%_ensure_resolvedr$r1r(rPrSr Zstaggered_racerrallrHr&r>_create_connection_transportrget_extra_inforr )rfrr;r<rTr=r?r)r*rUrrrVrWinfosr,rRrnrr)rr^rbrfrcreate_connections               zBaseEventLoop.create_connectionc s|d|}|}|rHt|tr*dn|} |j||| ||||d} n||||} z|IdHWn| YnX| |fS)NFrrr)rKrdrboolrrr) rfr*rrTrrrrrrrnrrrrf%s* z*BaseEventLoop._create_connection_transportc s|rtdt|dtjj}|tjjkr:td||tjjkrz|||||IdHWStj k r}z |sxW5d}~XYnX|std|| ||||IdHS)aSend a file to transport. Return the total number of bytes which were sent. The method uses high-performance os.sendfile if available. file must be a regular file object opened in binary mode. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. fallback set to True makes asyncio to manually read and send the file when the platform does not support the sendfile syscall (e.g. Windows or SSL socket on Unix). Raise SendfileNotAvailableError if the system does not support sendfile syscall and fallback is False. zTransport is closingZ_sendfile_compatiblez(sendfile is not supported for transport NzHfallback is disabled and native sendfile is not supported for transport ) rirmrrZ _SendfileModeZ UNSUPPORTEDZ TRY_NATIVE_sendfile_nativerr4_sendfile_fallback)rfrnr6r7r8r1rGrWrrrsendfile?s4   zBaseEventLoop.sendfilecstddS)Nz!sendfile syscall is not supportedr:)rfrgr6r7r8rrrrlnszBaseEventLoop._sendfile_nativec s|r|||rt|dnd}t|}d}t|}z|rXt|||}|dkrX|WbSt|d|} |d|j| IdH} | s|W0S| IdH| | d| || 7}q6W5|dkrt|dr||||IdHXdS)Ni@rr<) r<r=r>r\r#r{r?rr@rkwrite) rfrgr6r7r8rArBrCr?rDrErrrrmrs* z BaseEventLoop._sendfile_fallbackrjc stdkrtdt|tjs*td|t|ddsFtd|d|}tj|||||||dd}| | || |j |} | |j } z|IdHWn.tk r|| | YnX|jS) zzUpgrade transport to TLS. Return a new transport that *protocol* should start using immediately. Nz"Python ssl module is not availablez@sslcontext is expected to be an instance of ssl.SSLContext, got Z_start_tls_compatibleFz transport z is not supported by start_tls())rr)rTrmrZ SSLContextr5rrdr Z SSLProtocolrarbrrory BaseExceptionrrzZ_app_transport) rfrnrrrrrrZ ssl_protocolZ conmade_cbZ resume_cbrrr start_tlssB      zBaseEventLoop.start_tls)r=r?r) reuse_address reuse_portallow_broadcastr*c s| dk r| jtjkr"td| s>s>|s>|s>|s>|s>| r~t|||||| d} ddd| D} td| d| d d} nss|d krtd ||fd ff}nttd r|tj krfD]}|dk rt |t st dqڈrxd dkrxz"t t jr.tWnFtk rFYn2tk rv}ztd|W5d}~XYnX||ffff}ni}d fdffD]\}}|dk rt |trt|dkstd|j||tj|||dIdH}|std|D]:\}}}}}||f}||kr0ddg||<||||<qqfdd|D}|sjtdg}|tk r|rtdntjdtdd|D]\\}}\}}d} d} zxtj|tj|d} |rt| | r| tj tj!d| d r| "|r*| s&|#| |IdH|} Wn^tk rl}z | dk rR| $|%|W5d}~XYn&| dk r| $YnXqq|d |}|&}|'| || |}|j(rrt)d||nt*d||z|IdHWn|$YnX||fS)zCreate datagram connection.NzA UDP Socket was expected, got )rU remote_addrr=r?r)rrrsrtr%css$|]\}}|r|d|VqdS)=Nr)rCkvrrrrEsz9BaseEventLoop.create_datagram_endpoint..zKsocket modifier keyword arguments can not be used when sock is specified. ()Frzunexpected address family)NNAF_UNIXzstring is expected)rz2Unable to check or remove stale UNIX socket %r: %rrr!z2-tuple is expectedrZr[cs8g|]0\}}r|ddksr,|ddks||fqS)rNrr)rCkeyZ addr_pairrUrurrrs   z:BaseEventLoop.create_datagram_endpoint..zcan not get address informationz~Passing `reuse_address=True` is no longer supported, as the usage of SO_REUSEPORT in UDP poses a significant security concern.zdThe *reuse_address* parameter has been deprecated as of 3.5.10 and is scheduled for removal in 3.11.) stacklevelrIz@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))+r>r$r2r%dictr&itemsrKr#rzrrr5statS_ISSOCKosst_moderemoveFileNotFoundErrorr(rerrorrrrrd_unsetrrr"r+r&r'Z SO_BROADCASTrLrQrr9rdrrr(r ) rfrrUrur=r?r)rrrsrtr*ZoptsZproblemsZr_addrZaddr_pairs_inforOerrZ addr_infosidxrhZfamrRZprorr|rZ local_addressZremote_addressrWrrrnrr}rcreate_datagram_endpoints*                  z&BaseEventLoop.create_datagram_endpointc s\|dd\}}t|||||f|dd} | dk r<| gS|j||||||dIdHSdS)Nr!r/)rAr') rfrr=r>r?r)rr;r<r(rrrrdLs zBaseEventLoop._ensure_resolvedcs8|j||f|tj||dIdH}|s4td|d|S)N)r=r>r)rz getaddrinfo(z) returned empty list)rdr$r1r()rfr;r<r=r)rhrrr_create_server_getaddrinfoXs  z(BaseEventLoop._create_server_getaddrinfor) r=r)r*rrTrrrsrrc  st|trtd| dk r*|dkr*td|dk s<dk r"|dk rLtd| dkrhtjdkoftjdk} g} |dkr|dg}n$t|tst|t j j s|g}n|}fdd |D}t j |d iIdH}ttj|}d }z|D]}|\}}}}}zt|||}Wn8tjk rHjr@tjd |||d dYqYnX| || rl|tjtjd | rzt|tr|tjkrttdr|tj tj!d z|"|Wqt#k r}z t#|j$d||j%&fdW5d}~XYqXqd }W5|s| D]}|qXn4|dkr4td|j'tj(krPtd||g} | D]}|)d qZt*| |||| }| r|+t j,ddIdHjrt-d||S)a1Create a TCP server. The host parameter can be a string, in that case the TCP server is bound to host and port. The host parameter can also be a sequence of strings and in that case the TCP server is bound to all hosts of the sequence. If a host appears multiple times (possibly indirectly e.g. when hostnames resolve to the same IP address), the server is only bound once to that host. Return a Server object which can be used to stop the service. This method is a coroutine. z*ssl argument must be an SSLContext or NoneNrXrYposixcygwinr.csg|]}j|dqS))r=r))r)rCr;r=r)r<rfrrrs z/BaseEventLoop.create_server..rFz:create_server() failed to create socket.socket(%r, %r, %r)Texc_info IPPROTO_IPV6z0error while attempting to bind on address %r: %sz)Neither host/port nor sock were specifiedrcrrz %r is serving).rrkr5r%rrrplatformrrFabcIterabler rsetrKrLrMrr$rrrwarningr9r&r'Z SO_REUSEADDRr+r8rr#rZ IPV6_V6ONLYrLr(rOrMrNr>r1rKrrrr()rfrr;r<r=r)r*rrTrrrsrrrZhostsZfsrhZ completedresr@Zsocktyper?Z canonnameZsarrrrr create_server`s         zBaseEventLoop.create_server)rTrcsv|jtjkrtd||dk r.|s.td|j|||dd|dIdH\}}|jrn|d}td|||||fS) aHandle an accepted connection. This is used by servers that accept connections outside of asyncio but that use asyncio to handle connections. This method is a coroutine. When completed, the coroutine returns a (transport, protocol) pair. rcNrXr.T)rrr$z%r handled: (%r, %r)) r>r$r1r%rfrrgrr )rfrr*rTrrnrrrrconnect_accepted_sockets$   z%BaseEventLoop.connect_accepted_socketcsd|}|}||||}z|IdHWn|YnX|jr\td|||||fS)Nz Read pipe %r connected: (%r, %r))rdrrrrr filenorfrrrrrnrrrconnect_read_pipeszBaseEventLoop.connect_read_pipecsd|}|}||||}z|IdHWn|YnX|jr\td|||||fS)Nz!Write pipe %r connected: (%r, %r))rdrrrrr rrrrrconnect_write_pipesz BaseEventLoop.connect_write_pipecCs|g}|dk r"|dt||dk rJ|tjkrJ|dt|n8|dk rf|dt||dk r|dt|td|dS)Nzstdin=zstdout=stderr=zstdout=zstderr= )r9r!rrrr r&)rfr*rrrr(rrr_log_subprocessszBaseEventLoop._log_subprocess) rrruniversal_newlinesrrencodingerrorstextc st|ttfstd|r"td|s.td|dkr>td| rJtd| dk rZtd| dk rjtd|} d}|jrd |}||||||j| |d ||||f| IdH}|jr|dk rtd |||| fS) Nzcmd must be a string universal_newlines must be Falsezshell must be Truerbufsize must be 0text must be Falseencoding must be Noneerrors must be Nonezrun shell command %rT%s: %r) rr3rr%rrrrr()rfrcmdrrrrrrrrrrr debug_logrnrrrsubprocess_shellsB zBaseEventLoop.subprocess_shellc s|r td|rtd|dkr(td| r4td| dk rDtd| dk rTtd|f| }|}d}|jrd|}||||||j||d ||||f| IdH}|jr|dk rtd ||||fS) Nrzshell must be Falserrrrrzexecute program Fr)r%rrrrr()rfrZprogramrrrrrrrrrrrZ popen_argsrrrnrrrsubprocess_execCs@   zBaseEventLoop.subprocess_execcCs|jS)zKReturn an exception handler, or None if the default one is in use. )rrqrrrget_exception_handleresz#BaseEventLoop.get_exception_handlercCs(|dk rt|std|||_dS)aSet handler as the new event loop exception handler. If handler is None, the default exception handler will be set. If handler is a callable object, it should have a signature matching '(loop, context)', where 'loop' will be a reference to the active event loop, 'context' will be a dict object (see `call_exception_handler()` documentation for details about context). Nz+A callable object or None is expected, got )rr5r)rfZhandlerrrrset_exception_handlerjs z#BaseEventLoop.set_exception_handlerc Cs|d}|sd}|d}|dk r6t|||jf}nd}d|kr`|jdk r`|jjr`|jj|d<|g}t|D]}|dkr|qn||}|dkrd t|}d }|| 7}n2|dkrd t|}d }|| 7}nt |}| |d |qnt j d ||ddS)aEDefault exception handler. This is called when an exception occurs and no exception handler is set, and can be called by a custom exception handler that wants to defer to the default behavior. This default handler logs the error message and other context-dependent information. In debug mode, a truncated stack trace is also appended showing where the given object (e.g. a handle or future or task) was created, if any. The context parameter has the same meaning as in `call_exception_handler()`. rz!Unhandled exception in event looprRNFZsource_tracebackZhandle_traceback>rRrr.z+Object created at (most recent call last): z+Handle created at (most recent call last): rJ r)getr> __traceback__rrsortedr& traceback format_listrstriprr9rr) rfr rrRrZ log_linesr|valuetbrrrdefault_exception_handler{s<   z'BaseEventLoop.default_exception_handlerc Cs|jdkrVz||Wqttfk r2Yqtk rRtjdddYqXnz|||Wnttfk rYnttk r}zVz|d||dWn:ttfk rYn"tk rtjdddYnXW5d}~XYnXdS)aDCall the current event loop's exception handler. The context argument is a dict containing the following keys: - 'message': Error message; - 'exception' (optional): Exception object; - 'future' (optional): Future instance; - 'task' (optional): Task instance; - 'handle' (optional): Handle instance; - 'protocol' (optional): Protocol instance; - 'transport' (optional): Transport instance; - 'socket' (optional): Socket instance; - 'asyncgen' (optional): Asynchronous generator that caused the exception. New keys maybe introduced in the future. Note: do not overload this method in an event loop subclass. For custom exception handling, use the `set_exception_handler()` method. Nz&Exception in default exception handlerTrz$Unhandled error in exception handler)rrRr zeException in default exception handler while handling an unexpected error in custom exception handler)rrrSrTrprr)rfr rWrrrrs4  z$BaseEventLoop.call_exception_handlercCs>t|tjstd|jrdSt|tjr.t|j|dS)z3Add a Handle to _scheduled (TimerHandle) or _ready.zA Handle is required hereN)rrrr _cancelledrrr9rfrrrr _add_callbacks zBaseEventLoop._add_callbackcCs|||dS)z6Like _add_callback() but called from a signal handler.N)rrrrrr_add_callback_signalsafes z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)z3Notification that a TimerHandle has been cancelled.rN)rrrrrr_timer_handle_cancelledsz%BaseEventLoop._timer_handle_cancelledc Cst|j}|tkr`|j|tkr`g}|jD]}|jrsd                  ;   Do