Yfi@sdZddlZddlTddlZddlZddlZddlZddlmZyddlZWne k rdZYnXe eddZ e eddZ e ed dZ d d d d dgZejejeejd eddejdedddZdZddZeZejjjdriZdedrde"dd?d>Z#n"e$e"dd@d>Z#ejd>dAe#_e e hZ%GdBdCdCej&Z'dDdEd Z(e)Z*e*ddFd Z+dddddGdHZ,dS)Ia0This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object. Functions: socket() -- create a new socket object socketpair() -- create a pair of new socket objects [*] fromfd() -- create a socket object from an open file descriptor [*] fromshare() -- create a socket object from data received from socket.share() [*] gethostname() -- return the current hostname gethostbyname() -- map a hostname to its IP number gethostbyaddr() -- map an IP number or hostname to DNS info getservbyname() -- map a service name and a protocol name to a port number getprotobyname() -- map a protocol name (e.g. 'tcp') to a number ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order htons(), htonl() -- convert 16, 32 bit int from host to network byte order inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) socket.getdefaulttimeout() -- get the default timeout value socket.setdefaulttimeout() -- set the default timeout value create_connection() -- connects to an address, with an optional timeout and optional source address. [*] not available on all platforms! Special objects: SocketType -- type object for socket objects error -- exception raised for I/O errors has_ipv6 -- boolean value indicating if IPv6 is supported IntEnum constants: AF_INET, AF_UNIX -- socket domains (first argument to socket() call) SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) Integer constants: Many other constants may be defined; these may be used in calls to the setsockopt() and getsockopt() methods. N)*)IntEnumEBADF EAGAIN EWOULDBLOCKfromfdgetfqdncreate_connection AddressFamily SocketKindcCs|jo|jdS)NZAF_)isupper startswith)Cr+/opt/alt/python35/lib64/python3.5/socket.pyLsrcCs|jo|jdS)NZSOCK_)rr)rrrrrQsz 127.0.0.1z::1c Cs+y||SWntk r&|SYnXdS)z{Convert a numeric family value to an IntEnum member. If it's not a known member, return the numeric value itself. N) ValueError)valueZ enum_klassrrr_intenum_converterWs rwinzThe operation was interrupted.i'zA bad file handle was passed.i'zPermission denied.i'z!A fault occurred on the network??i'z#An invalid operation was attempted.i&'z The socket operation would blocki3'z,A blocking operation is already in progress.i4'zThe network address is in use.i@'zThe connection has been reset.iF'zThe network has been shut down.iJ'zThe operation timed out.iL'zConnection refused.iM'zThe name is too long.iO'zThe host is down.iP'zThe host is unreachable.iQ'errorTabc@seZdZdS)_GiveupOnSendfileN)__name__ __module__ __qualname__rrrrrxs rc seZdZdZdddgZeeddddZd d Zd d Z d dZ ddZ ddZ ddZ ddddddddddZeedrddddZnddddZdddd Zd!d"Zddd#d$Zd%d&Zejd'd(Zd)d*Zfd+d,Zefd-d.Zefd/d0Zejd1krd2d3Zd4d5Z nd6d3Zd7d5Z d8e_d9e _S):socketz:A subclass of _socket.socket adding the makefile() method. __weakref___io_refs_closedrNcCs2tjj|||||d|_d|_dS)NrF)_socketr__init__rr )selffamilytypeprotofilenorrrr"s zsocket.__init__cCs|S)Nr)r#rrr __enter__szsocket.__enter__cGs|js|jdS)N)r close)r#argsrrr__exit__s zsocket.__exit__cCst|dd}d|jj|jj|r3dnd|j|j|j|jf}|sy*|j}|r|dt |7}Wnt k rYnXy*|j }|r|dt |7}Wnt k rYnX|d7}|S) zVWrap __repr__() to reveal the real class name and socket address(es). r Fz,<%s.%s%s fd=%i, family=%s, type=%s, proto=%iz [closed]z , laddr=%sz , raddr=%s>) getattr __class__rrr'r$r%r& getsocknamestrerrorZ getpeername)r#closedsZladdrZraddrrrr__repr__s0         zsocket.__repr__cCstddS)NzCannot serialize socket object) TypeError)r#rrr __getstate__szsocket.__getstate__cCsMt|j}|j|j|j|jd|}|j|j|S)zdup() -> socket object Duplicate the socket. Return a new socket object connected to the same system resource. The new socket is non-inheritable. r')dupr'r/r$r%r& settimeout gettimeout)r#fdsockrrrr8s$z socket.dupcCs|j\}}|jtjdd@}t|j||jd|}tdkru|jru|j d||fS)zaccept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port). Z SOCK_NONBLOCKrr'NT) Z_acceptr%globalsgetrr$r&Zgetdefaulttimeoutr: setblocking)r#r;addrr%r<rrraccepts  z socket.acceptrencodingerrorsnewlinec Cst|dddhks.td|fd|k}d|kpJ| }|s_|s_td|k}d} |r| d7} |r| d7} t|| } |jd7_|dkrd }|dkrtj}|dkr|std | S|r|rtj| | |} n9|r7tj| |} n|sCttj | |} |r_| Stj | |||} || _ | S) zmakefile(...) -> an I/O stream connected to the socket The arguments are as for io.open() after the filename, except the only supported mode values are 'r' (default), 'w' and 'b'. rBwbz&invalid mode %r (only r, w, b allowed)r,Nrz!unbuffered streams must be binary) setrAssertionErrorSocketIOrioDEFAULT_BUFFER_SIZEBufferedRWPairBufferedReaderBufferedWriter TextIOWrappermode) r#rS bufferingrCrDrEZwritingZreadingZbinaryZrawmoderawbuffertextrrrmakefiles@            zsocket.makefilesendfilec2Csm|j||||j}y|j}Wn:ttjfk rk}zt|WYdd}~XnXytj|j}Wn1t k r}zt|WYdd}~XnX|sdS|s|n|}|j } | dkrt dt t drt j} n t j} | j|t jd} | j} tj} zx| rs| |  rstjd|r|| }|dkrPy| ||||}Wngtk r| s| wQYqQt k r}z&| dkrt||dWYdd}~XqQX|dkr P||7}| |7} qQW| SWd| dkrht |drh|j|XdS)Nrz&non-blocking sockets are not supported PollSelectorz timed outseek)_check_sendfile_paramsr'AttributeErrorrMUnsupportedOperationrosfstatst_sizeOSErrorr:rhasattr selectorsrZZSelectSelectorregisterZ EVENT_WRITEZselectrYr!timeoutBlockingIOErrorr[)r#fileoffsetcountZsocknor'errZfsize blocksizerfZselector total_sentZselector_selectZ os_sendfilesentrrr_sendfile_use_sendfiles`              zsocket._sendfile_use_sendfilecCstddS)Nz,os.sendfile() not available on this platform)r)r#rhrirjrrrro=sc CsX|j||||jdkr1td|rD|j||rYt|dnd}d}|j}|j}zx|rt|||}|dkrPt||}|sPx\y||} Wntk rwYqX|| 7}| t |kr|| d}qPqWq}W|SWd|dkrSt |drS|j||XdS)Nrz&non-blocking sockets are not supportedi r[) r\r:rr[minreadsend memoryviewrglenrc) r#rhrirjrlrmZ file_readZ sock_senddatarnrrr_sendfile_use_sendAs<        zsocket._sendfile_use_sendcCsdt|ddkr$td|jt@s=td|dk rt|tsmtdj||dkrtdj|dS)NrGrSz$file should be opened in binary modez+only SOCK_STREAM type sockets are supportedz+count must be a positive integer (got {!r})r)r.rr% SOCK_STREAM isinstanceintr6format)r#rhrirjrrrr\es     zsocket._check_sendfile_paramsc CsCy|j|||SWn%tk r>|j|||SYnXdS)a_sendfile(file[, offset[, count]]) -> sent Send a file until EOF is reached by using high-performance os.sendfile() and return the total number of bytes which were sent. *file* must be a regular file object opened in binary mode. If os.sendfile() is not available (e.g. Windows) or file is not a regular file socket.send() will be used instead. *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. The socket must be of SOCK_STREAM type. Non-blocking sockets are not supported. N)rorrv)r#rhrirjrrrrYrs zsocket.sendfilecCs5|jdkr|jd8_|jr1|jdS)NrrH)rr r))r#rrr_decref_socketioss zsocket._decref_socketioscCs|j|dS)N)r))r#Z_ssrrr _real_closeszsocket._real_closecCs&d|_|jdkr"|jdS)NTr)r rr|)r#rrrr)s z socket.closecsd|_tjS)a detach() -> file descriptor Close the socket object without closing the underlying file descriptor. The object cannot be used after this call, but the file descriptor can be reused for other purposes. The file descriptor is returned. T)r superdetach)r#)r/rrr~s z socket.detachcsttjtS)z@Read-only access to the address family for this socket. )rr}r$r )r#)r/rrr$sz socket.familycsttjtS)z-Read-only access to the socket type. )rr}r%r )r#)r/rrr%sz socket.typentcCstj|jS)N)r_Zget_handle_inheritabler')r#rrrget_inheritableszsocket.get_inheritablecCstj|j|dS)N)r_Zset_handle_inheritabler')r# inheritablerrrset_inheritableszsocket.set_inheritablecCstj|jS)N)r_rr')r#rrrrscCstj|j|dS)N)r_rr')r#rrrrrsz&Get the inheritable flag of the socketz&Set the inheritable flag of the socket)!rrr__doc__ __slots__AF_INETrwr"r(r+r5r7r8rArXrcr_rorvr\rYr{r!rr|r)r~propertyr$r%namerrrr)r/rr{s<       )A$        rcCst|}t||||S)z fromfd(fd, family, type[, proto]) -> socket object Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket(). )r8r)r;r$r%r&Znfdrrrr s ZsharecCstddd|S)z fromshare(info) -> socket object Create a socket object from the bytes object returned by socket.share(pid). r)r)inforrr fromsharesr socketpairc Cs|dkr1y t}Wntk r0t}YnXtj|||\}}t||||j}t||||j}||fS)aasocketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET. N)ZAF_UNIX NameErrorrr!rrr~)r$r%r&arGrrrrs    c CsY|tkrt}n!|tkr*t}n td|tkrNtd|dkrftdt|||}z|j|df|j|j dd\}}t|||}yb|j dy|j ||fWnt t fk rYnX|j d|j\}} Wn|jYnXWd|jX||fS)Nz?Only AF_INET and AF_INET6 socket address families are supportedz)Only SOCK_STREAM socket type is supportedrzOnly protocol zero is supportedFT)r _LOCALHOSTZAF_INET6 _LOCALHOST_V6rrwrbindZlistenr0r?connectrgInterruptedErrorrAr)) r$r%r&hostZlsockr@portZcsockZssock_rrrrs8               a8socketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET. cseZdZdZddZddZddZdd Zd d Zfd d Z ddZ e ddZ e ddZ ddZS)rLzRaw I/O implementation for stream sockets. This class supports the makefile() method on sockets. It provides the raw I/O interface on top of a socket object. cCs|d krtd|tjj|||_d|krK|d7}||_d|k|_d|k|_d |_dS) NrBrFrwrbwbrwbzinvalid mode: %rrGF)rBrFrrrr) rrM RawIOBaser"_sock_mode_reading_writing_timeout_occurred)r#r<rSrrrr"&s     zSocketIO.__init__cCs|j|j|jr)tdxwy|jj|SWq,tk r`d|_Yq,tk r}z|jdt krdSWYdd}~Xq,Xq,WdS)a3Read up to len(b) bytes into the writable buffer *b* and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned. If *b* is non-empty, a 0 return value indicates that the connection was shutdown at the other end. z!cannot read from timed out objectTrN) _checkClosed_checkReadablerrbrZ recv_intorfr2r*_blocking_errnos)r#rGerrrreadinto2s      zSocketIO.readintocCsn|j|jy|jj|SWn?tk ri}z|jdtkrTdSWYdd}~XnXdS)aWrite the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. rN)r_checkWritablerrrr2r*r)r#rGrrrrwriteIs  zSocketIO.writecCs|jrtd|jS)z2True if the SocketIO is open for reading. zI/O operation on closed socket.)r3rr)r#rrrreadableYs  zSocketIO.readablecCs|jrtd|jS)z2True if the SocketIO is open for writing. zI/O operation on closed socket.)r3rr)r#rrrwritable`s  zSocketIO.writablecs"|jrtdtjS)z2True if the SocketIO is open for seeking. zI/O operation on closed socket.)r3rr}seekable)r#)r/rrrgs  zSocketIO.seekablecCs|j|jjS)z=Return the file descriptor of the underlying socket. )rrr')r#rrrr'ns zSocketIO.filenocCs|js|jSdSdS)NrHrI)r3r')r#rrrrts  z SocketIO.namecCs|jS)N)r)r#rrrrS{sz SocketIO.modecCs7|jr dStjj||jjd|_dS)zClose the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. N)r3rMrr)rr{)r#rrrr)s   zSocketIO.close)rrrrr"rrrrrr'rrrSr)rr)r/rrLs      rLr,c Cs|j}| s|dkr(t}yt|\}}}Wntk rUYn5X|jd|x!|D]}d|krmPqmW|}|S)aGet fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned. z0.0.0.0r.)stripZ gethostnameZ gethostbyaddrr2insert)rZhostnamealiasesZipaddrsrrrr s     cCs |\}}d}xt||dtD]}|\}}} } } d} ySt||| } |tk rw| j||r| j|| j| | SWq(tk r} z!| }| dk r| jWYdd} ~ Xq(Xq(W|dk r|n tddS)acConnect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. A host of '' or port 0 tells the OS to use the default. Nrz!getaddrinfo returns an empty list) getaddrinforwr_GLOBAL_DEFAULT_TIMEOUTr9rrr2r))ZaddressrfZsource_addressrrrkresafsocktyper& canonnamesar<rrrrr s(      !  c Csvg}xitj||||||D]I}|\}} }} } |jt|tt| t|| | fq%W|S)aResolve host and port into list of address info entries. Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representation of an IPv4/v6 address or None. port is a string service name such as 'http', a numeric port number or None. By passing None as the value of host and port, you can pass NULL to the underlying C API. The family, type and proto arguments can be optionally specified in order to narrow the list of addresses returned. Passing zero as a value for each of these arguments selects the full range of results. )r!rappendrr r ) rrr$r%r&flagsZaddrlistrrrrrrrrrs% r)-rr!r_sysrMrdZenumrerrno ImportErrorr.rrr__all__extend_get_exports_list_convertrrrrrZ _realsocketplatformlowerrrr Exceptionrr rcrrwrrrrrLr objectrr rrrrr/s~  0                       B   $   u %