ϪfHdZddlZddlZddlZddlmZddlmZddlm Z e dk(r3ddl m Z ddl m Z dd l m Z mZmZmZmZmZmZee ee gZe eeegZeZe Ze ZeZndd l mZmZmZmZmZmZeeegZegZdd lmZmZmZm Z m!Z!m"Z"dd l#m$Z$m%Z%ee"jLe"jNe"jPGd dejRZ*GddZ+ee"jXGdde+e*Z-y)a Various asynchronous UDP classes. Please do not use this module directly. @var _sockErrReadIgnore: list of symbolic error constants (from the C{errno} module) representing socket errors where the error is temporary and can be ignored. @var _sockErrReadRefuse: list of symbolic error constants (from the C{errno} module) representing socket errors that indicate connection refused. N)Optional) implementer) platformTypewin32)WSAEINPROGRESS)WSAEWOULDBLOCK)WSAECONNREFUSED WSAECONNRESETWSAEINTR WSAEMSGSIZE WSAENETRESETWSAENOPROTOOPT WSAETIMEDOUT)EAGAIN ECONNREFUSEDEINTREMSGSIZE ENOPROTOOPT EWOULDBLOCK)abstractaddressbasedefererror interfaces)failurelogceZdZUdZej ZejZdZ dZ e e e d<dZddZedZdefdZd Zd Zd Zd Zd ZddZdZdZdZdZdZddZdZ dZ!dZ"dZ#dZ$dZ%y)Porta UDP port, listening for packets. @ivar maxThroughput: Maximum number of bytes read in one event loop iteration. @ivar addressFamily: L{socket.AF_INET} or L{socket.AF_INET6}, depending on whether this port is listening on an IPv4 address or an IPv6 address. @ivar _realPortNumber: Actual port number being listened on. The value will be L{None} until this L{Port} is listening. @ivar _preexistingSocket: If not L{None}, a L{socket.socket} instance which was created and initialized outside of the reactor and will be used to listen for connections (instead of a new socket being created by this L{Port}). iN_realPortNumberctjj||||_||_||_||_|jd|_|jy)a @param port: A port number on which to listen. @type port: L{int} @param proto: A C{DatagramProtocol} instance which will be connected to the given C{port}. @type proto: L{twisted.internet.protocol.DatagramProtocol} @param interface: The local IPv4 or IPv6 address to which to bind; defaults to '', ie all IPv4 addresses. @type interface: L{str} @param maxPacketSize: The maximum packet size to accept. @type maxPacketSize: L{int} @param reactor: A reactor which will notify this C{Port} when its socket is ready for reading or writing. Defaults to L{None}, ie the default global reactor. @type reactor: L{interfaces.IReactorFDSet} N) rBasePort__init__portprotocol maxPacketSize interface setLogStr_connectedAddr_setAddressFamily)selfr$protor'r&reactors 6/usr/lib/python3/dist-packages/twisted/internet/udp.pyr#z Port.__init__[sS* tW-  *" "  ctj|||j}|jd}|d||||}||_|S)a Create a new L{Port} based on an existing listening I{SOCK_DGRAM} socket. @param reactor: A reactor which will notify this L{Port} when its socket is ready for reading or writing. Defaults to L{None}, ie the default global reactor. @type reactor: L{interfaces.IReactorFDSet} @param fd: An integer file descriptor associated with a listening socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @type fd: L{int} @param addressFamily: The address family (sometimes called I{domain}) of the existing socket. For example, L{socket.AF_INET}. @type addressFamily: L{int} @param protocol: A C{DatagramProtocol} instance which will be connected to the C{port}. @type protocol: L{twisted.internet.protocol.DatagramProtocol} @param maxPacketSize: The maximum packet size to accept. @type maxPacketSize: L{int} @return: A new instance of C{cls} wrapping the socket given by C{fd}. @rtype: L{Port} rN)r'r-r&)socketfromfd socketType getsockname_preexistingSocket) clsr-fd addressFamilyr%r&r$r'r+s r._fromListeningDescriptorzPort._fromListeningDescriptorysV@}}R?$$&q)   '  #' r/returnc|j'd|jjd|jdSd|jjdS)Nz not connected>)r r% __class__r+s r.__repr__z Port.__repr__sO    +t}}../tD4H4H3IK Kt}}../? ?r/c|jS)z) Return a socket object. )r1r?s r. getHandlezPort.getHandle{{r/cD|j|jy)z Create and bind my socket, and begin listening on it. This is called on unserialization, and must be called after creating a server to begin listening on the specified port. N) _bindSocket_connectToProtocolr?s r.startListeningzPort.startListenings  !r/c(|j9 |j}|j|j|jfn|j}d|_|jd|_ tj|j|jd|jd|_||_|jj |_y#t $r0}t j|j|j|d}~wwxYw)aJ Prepare and assign a L{socket.socket} instance to C{self.socket}. Either creates a new SOCK_DGRAM L{socket.socket} bound to C{self.interface} and C{self.port} or takes an existing L{socket.socket} provided via the L{interfaces.IReactorSocket.adoptDatagramPort} interface. Nz starting on )r5createInternetSocketbindr'r$OSErrorrCannotListenErrorr4r rmsg _getLogPrefixr% connectedr1filenor+sktles r.rEzPort._bindSockets  " " * M//1$..$))45 ))C&*D # #03 !!$--0$2F2F H  kk(( % M--dnndiiLL Ms7C D!+D  DcZ|jj||jyN)r%makeConnection startReadingr?s r.rFzPort._connectToProtocols  $$T* r/c<d}||jkr |jj|j\}}|t |z }|j tj k(r|dd} |jj||||jkryy#t$rtjY1wxYw#t$rU}|jd}|tvrYd}~y|tvr+|j r|jj#Yd}~yd}~wwxYw)z= Called when my socket is ready for reading. rN) maxThroughputr1recvfromr&lenr8AF_INET6r%datagramReceived BaseExceptionrerrrLargs_sockErrReadIgnore_sockErrReadRefuser)connectionRefused)r+readdataaddrsenos r.doReadz Port.doReadsT''' ![[11$2D2DE dD !%%8 8DMM224>/T'''0%GGI+ WWQZ++++** 779 s5(B=,BB:9B:= DD".DDDc|jr.|d|jfvsJ |jj|S|dk7sJtj|ds9tj|ds!|ddk7rtj |ddtj|ds|ddk(r6|j"tj$k(rtj |ddtj|dr6|j"tj&k(rtj |dd |jj)||S#t$r{}|jd}|t k(r|j |cYd}~S|tk(rtjd|tk(r|jjnYd}~yd}~wwxYw#t$ra}|jd}|t k(r|j ||cYd}~S|tk(rtjd|tk(rYd}~yd}~wwxYw)az Write a datagram. @type datagram: L{bytes} @param datagram: The datagram to be sent. @type addr: L{tuple} containing L{str} as first element and L{int} as second element, or L{None} @param addr: A tuple of (I{stringified IPv4 or IPv6 address}, I{integer port number}); can be L{None} in connected mode. Nrzmessage too longz z0write() only accepts IP addresses, not hostnamesz7IPv6 port write() called with IPv4 or broadcast addressz*IPv4 port write() called with IPv6 address)r)r1sendrLrbrwriterrMessageLengthErrorrr%rer isIPAddress isIPv6AddressInvalidAddressErrorr8r^AF_INETsendto)r+datagramrhrirjs r.rnz Port.writes   D$"5"566 66 {{''114< <((a1 ..tAw7G},//GO$$T!W-aM1I$$7//GV%%d1g.43E3E3W//GI {{))(D99? WWQZ;::h//8^223EFF<'MM3356 @ WWQZ;::h558^223EFF<' sNE8G G(GG AGG I$)I I'I?IIcF|jdj||y)a Write a datagram constructed from an iterable of L{bytes}. @param seq: The data that will make up the complete datagram to be written. @type seq: an iterable of L{bytes} @type addr: L{tuple} containing L{str} as first element and L{int} as second element, or L{None} @param addr: A tuple of (I{stringified IPv4 or IPv6 address}, I{integer port number}); can be L{None} in connected mode. r/N)rnjoin)r+seqrhs r. writeSequencezPort.writeSequence@s 388C=$'r/c|jr tdtj|s+tj|st j |d||f|_|jj||fy)z- 'Connect' to remote server. z:already connected, reconnecting is not currently supportednot an IPv4 or IPv6 address.N) r) RuntimeErrorrrprqrrrr1connect)r+hostr$s r.r}z Port.connectOsp   L ##D)(2H2H2N++D2PQ Q#Tl T4L)r/c|j|jr'|jjd|jyy)Nr) stopReadingrPr- callLaterconnectionLostr?s r._loseConnectionzPort._loseConnection\s4  >> LL " "1d&9&9 : r/cz|jrtjx}|_nd}|j |SrV)rPrDeferreddr)r+results r. stopListeningzPort.stopListeningas2 >>#nn. .FTVF  r/c\tjdtd|jy)Nz-Please use stopListening() to disconnect portrZ) stacklevel)warningswarnDeprecationWarningrr?s r.loseConnectionzPort.loseConnectionis% ;  r/chtjd|jzd|_d|_tj j |||jj|jj|` |` t|dr|jjd|` yy)z& Cleans up my socket. z(UDP Port %s Closed)Nr)rrNr r[rr"rr%doStopr1closerQhasattrrcallback)r+reasons r.rzPort.connectionLostqs &)=)==># $$T62   K K 4  FFOOD ! r/cN|j|j}d|z|_y)zP Initialize the C{logstr} attribute to be used by C{logPrefix}. z%s (UDP)N)rOr%logstr)r+ logPrefixs r.r(zPort.setLogStrs$&&t}}5  9, r/c0tj|jrtj|_ytj |jrtj|_y|jr tj|jdy)z8 Resolve address family for the socket. r{N) rrqr'r1r^r8rprsrrrr?s r.r*zPort._setAddressFamilysi  ! !$.. 1!'D   ! !$.. 1!'D  ^^++ > r/c|jS)z0 Return the prefix to log with. )rr?s r.rzPort.logPrefixrCr/c |jj}|jtjk(rt j dg|S|jtj k(rt jdg|ddSy)z Return the local address of the UDP connection @returns: the local address of the UDP connection @rtype: L{IPv4Address} or L{IPv6Address} UDPNrZ)r1r4r8rsr IPv4Addressr^ IPv6Addressr+rhs r.getHostz Port.getHostsq{{&&(    /&&u4t4 4   6?? 2&&u:Ra: :3r/cv|jjtjtj|y)z Set whether this port may broadcast. This is disabled by default. @param enabled: Whether the port may broadcast. @type enabled: L{bool} N)r1 setsockopt SOL_SOCKET SO_BROADCAST)r+enableds r.setBroadcastAllowedzPort.setBroadcastAlloweds& v00&2E2EwOr/ct|jjtjtjS)z Checks if broadcast is currently allowed on this port. @return: Whether this port may broadcast. @rtype: L{bool} )boolr1 getsockoptrrr?s r.getBroadcastAllowedzPort.getBroadcastAlloweds,DKK**6+<+Q>QRSSr/) NrV)&__name__ __module__ __qualname____doc__r1rsr8 SOCK_DGRAMr3r[r rint__annotations__r5r# classmethodr9strr@rBrGrErFrkrnryr}rrrrr(r*rrrrr/r.rr>s$NNM""JM%)OXc])!<))V@#@  "!)F@<| ( *;  -  ;PTr/rcVeZdZdZdZdZdZdZdZdZ dZ dd Z d Z d Z dd Zy )MulticastMixinz, Implement multicast functionality. c|jjtjtj}tjt j d|S)Nz@i)r1r IPPROTO_IPIP_MULTICAST_IF inet_ntoastructpack)r+is r.getOutgoingInterfacez#MulticastMixin.getOutgoingInterfaces@ KK " "6#4#4f6L6L M D! 455r/cj|jj|j|jS)zReturns Deferred of success.)r-resolve addCallback _setInterfacers r.setOutgoingInterfacez#MulticastMixin.setOutgoingInterfaces(||##D)55d6H6HIIr/ctj|}|jjtjtj|y)NrI)r1 inet_atonrrr)r+rhrs r.rzMulticastMixin._setInterfaces7   T " v00&2H2H!Lr/cr|jjtjtjSrV)r1rrIP_MULTICAST_LOOPr?s r.getLoopbackModezMulticastMixin.getLoopbackModes%{{%%f&7&79Q9QRRr/ctjdt|}|jj tj tj |y)Nb)rrrr1rrr)r+modes r.setLoopbackModezMulticastMixin.setLoopbackModes8{{3T + v00&2J2JDQr/cr|jjtjtjSrV)r1rrIP_MULTICAST_TTLr?s r.getTTLzMulticastMixin.getTTLs%{{%%f&7&79P9PQQr/ctjd|}|jjtjtj |y)NB)rrr1rrr)r+ttls r.setTTLzMulticastMixin.setTTLs4kk#s# v00&2I2I3Or/cn|jj|j|j|dS)z4Join a multicast group. Returns Deferred of success.rIr-rr _joinAddr1r+rhr's r. joinGroupzMulticastMixin.joinGroup+||##D)55dooyRSTTr/cn|jj|j|j||SrV)r-rr _joinAddr2)r+rhr'rws r.rzMulticastMixin._joinAddr1s+||##I.::4??DRVWWr/ctj|}tj|}|rtj}ntj} |jj tj |||zy#t $r>}tjtj||g|jcYd}~Sd}~wwxYwrV) r1rIP_ADD_MEMBERSHIPIP_DROP_MEMBERSHIPrrrLrFailurerMulticastJoinErrorrb)r+r'rhrwcmdes r.rzMulticastMixin._joinAddr2s%$$Y/ **C++C W KK " "6#4#4c4);K L W??5#;#;D)#Uaff#UV V Ws.A>> C3C:CCcn|jj|j|j|dS)z2Leave multicast group, return Deferred of success.rrrs r. leaveGroupzMulticastMixin.leaveGrouprr/N)r)rrrrrrrrrrrrrrrrr/r.rrsG6J SRRPUX WUr/rc&eZdZdZ ddZdZy) MulticastPortz. UDP Port that supports multicasting. NcFtj||||||||_y)zX @see: L{twisted.internet.interfaces.IReactorMulticast.listenMulticast} N)rr#listenMultiple)r+r$r,r'r&r-rs r.r#zMulticastPort.__init__s" dD%M7K,r/ctj|}|jrq|jtj tj dttdr2 |jtj tjd|S|S#t$r }|jtk(rnYd}~|Sd}~wwxYw)NrI SO_REUSEPORT) rrJrrr1r SO_REUSEADDRrrrLerrnorrRs r.rJz"MulticastPort.createInternetSockets''-    NN6,,f.A.A1 Ev~.NN6#4#4f6I6I1M s xx;. s"/B B>B99B>)rrNF)rrrrr#rJrr/r.rrs - r/r).rr1rrtypingrzope.interfacertwisted.python.runtimerrrrr r r r r rrrrcrdrrrrrtwisted.internetrrrrrrtwisted.pythonrrIListeningPort IUDPTransport ISystemHandler"rrIMulticastTransportrrr/r.rs  &/7$$#NKP)=, UH"L F EUU %5&ON' z779Q9QwT4==wTwTt 5U5Up Z + +,!ND!-!r/